Bill
Bill

Reputation: 45408

Storyboards: How do I use the same view controller in several places?

For years, I've hand-coded my view code for iPhone apps, but now I'm giving storyboards another look.

One common pattern in my code is to use the same view controller in two places, but with slight UI variations. For example, when browsing a list of brands (BrandListController), I'd like to show a table view of all brands in the system; tapping a brand shows you its products. But when filtering items by brand, I'd like to show a table view of brands (with the same content and same cell appearance), but I'd like tapping a row to take you back to the filter screen instead of showing you that brand's items. I'd also like a "Search" bar button item in the top right.

It's easy to make these things happen in code, by just adding a boolean member variable so the controller can be configured before it's presented.

But how would I do this with storyboards? I could have multiple controllers segue to the same instance of BrandListController, but again, I would want the controller to have different behavior and include/exclude UI elements based on how it's used. It seems like a bad idea to create two separate instances of BrandListController in the storyboard, because then I would have to duplicate all the outlet connections and I would have to keep changes in sync. But what are my other options?

Upvotes: 0

Views: 719

Answers (1)

Fogmeister
Fogmeister

Reputation: 77631

The thing to realise with Storyboards is that you don't necessarily have to only use a single storyboard.

You can use multiple storyboards or use them in conjunction with nibs etc...

However, in this case what you could do is still use you boolean property on the controller.

Then in the prepareForSegue method of the other controllers you can set this boolean property to change the behaviour. You might even have a couple of nibs that defines a small section of UI to place into the view depending on the property.

I've done stuff like this to pass blocks into view controller too.

For example...

I had a "User Search" controller that had a default behaviour of if you tap a user it will push to that user's profile page.

But I could pass in a code block that would, for instance, dismiss the search controller and I use the selected user to create a new message to them (or whatever). Or something else entirely depending on the code block I passed in.

EDIT

LOL, just re-read your question. What I did with the blocks would work for you too. I created a block property called userTappedBlock or something. If that exists then I run it when the cell is tapped. If not I do the default behaviour.

Upvotes: 3

Related Questions