Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reusing UIViewController for two Tab bar items

I have 1 tab bar controller in storyboard and 1 UIViewController associated with it. I would like to re-use the same UIViewController in order to create second item in tab bar. When I am creating second relation from tab bar to view controller I need to specify 2 different items names. How can I re-use same view controller and set different items names from storyboard? If not possible to do it in storyboard, then do I have to rename each in tab bar controller class or there is better way?

I was going to provide different data to view controller in prepareforsegue.

UPDATE:

little more details and clarification

enter image description here

In above screenshot marked VC at the moment is reachable a) directly from tab, b) through 3 transitions. I want to add another DIRECT relation to initial tab bar, just like in case of "a".

like image 531
Pablo Avatar asked Mar 18 '14 21:03

Pablo


2 Answers

I can give you a little tweak for that and at least that worked for me.

  1. Drag a tabbarcontroller and associated tab item view controllers to your storyboard. Name them as you like.
  2. Create an extra view controller that you want to reuse from your storyboard.
  3. Add container views to each tab item view controllers and remove their default embedded view controllers.
  4. Create embed segue from each tab item controller to your re-usuable view controller.

The configuration looks something like the following:

Screenshot

Thus you can use the same embedded VC for different tabbar item. Obviously if you need the reference of the tabbarcontroller, you need to use self.parentViewController.tabBarController instead of self.tabBarController directly. But it solves the issue of reusing a VC right from the storyboard.

like image 105
Ayan Sengupta Avatar answered Nov 16 '22 18:11

Ayan Sengupta


I've found much simpler solution using storyboard only.

Setup your storyboard like this:

Storyboard

Then in your Navigation Controller Identity Inspector set Restoration ID like this:

enter image description here

And in your ViewController class file put the following code:

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    self.navigationItem.title = parent?.restorationIdentifier
    label.text = parent?.restorationIdentifier
}

or do what you like based on parent?.restorationIdentifier value

If you don't want the Navigation TopBar to appear on the ViewController just set it to None in Attributes Inspector of the desired Navigation Controller like this:

enter image description here

That's it! Hope it helps.

like image 37
gutaker Avatar answered Nov 16 '22 20:11

gutaker