Tuesday, February 23, 2016

ios Embedded UITabBarController in UINavigationViewController

When designing ios App in storyboard, certain UITabBarController cannot be embedded into UINavigationviewController in the same way as other view controller.

One approach to solve the issue it just adding a regular UIViewController into the storyboard and embedded it into navigation view controller. And then add a view of TabBar into the UIViewController. With this approach, you will need to set the tabbar UIView's delegate by yourself.

Another approach is still using UITabBarController and then open the tabbarcontroller using show method from a segue. With this way, you get the full function provided by UITabBarController, but you cannot set the UINavigationBar's title and bar button from storyboard. Instead you will need to set them from the viewdidLoad() method as shown below.

  override func viewDidLoad() {
        super.viewDidLoad()
        
        self.navigationItem.title = "Settings"
        
        let leftButton : UIBarButtonItem = UIBarButtonItem(title: "Save", style: UIBarButtonItemStyle.Plain, target: self, action:"save:");
        leftButton.tintColor = UIColor.whiteColor()
        self.navigationItem.leftBarButtonItem = leftButton
        
        let rightButton : UIBarButtonItem = UIBarButtonItem(title: "Cancel", style: UIBarButtonItemStyle.Plain, target: self, action:"cancel:");
        rightButton.tintColor = UIColor.whiteColor()
        self.navigationItem.rightBarButtonItem = rightButton

    }
    

    func cancel(sender: UIBarButtonItem) {
        print("cancel clicked")
         self.performSegueWithIdentifier("returnToParent", sender: self)
        
    }
    
    func save(sender: UIBarButtonItem) {
        print("save clicked")
        
        self.performSegueWithIdentifier("saveAndReturnToParentt", sender: self)
    }
     
Option 2 seems better as most of the code required for the function is within the viewDidLoad method.

1 comment: