问题
My app has a UITabBar with four tabs... each with its own custom UIViewController. Three of them have a map plus other UI elements in common, in the same place on the screen.. in two of these views the map is initially hidden.
It seems like it would make more sense to make these three view the same instance of the same view controller.. and just hide/show elements. Is it possible to do this with the tab bar?
回答1:
I don't think those who answered "yes" read your question closely enough. You asked if it's possible to "make these three view the same instance of the same view controller". You can certainly use three different instances of the same UIViewController subclass, but I don't think you'll want to use the same instance.
I've honestly never tried this, but I wouldn't logically expect it to work for a couple reasons:
The title and icon shown for each tab is defined via the view controller's tabBarItem property. If the same UIViewController instance appeared multiple times in the tab bar controller's viewControllers array, then every tab would also share the same tabBarItem, meaning you'd have no way to give each tab a unique label and icon.
To conserve memory when you switch from one tab to another, UIKit will unload the view of the view controller that disappeared. If the view controller you've switched to is the same instance as the one that disappeared, UIKit may try to unload its view while it's being displayed. I'd expect this to create memory management bugs that could cause your app to crash with an EXC_BAD_ACCESS signal.
Rather than using the same instance for multiple tabs, I'd recommend one of these options:
A. Use the multiple instances of the same UIViewController subclass, and set properties to uniquely configure each instance.
B. Create a base UIViewController subclass that implements those aspects that are common to all three tabs, then create three subclasses of your base class that implement those aspects that are unique to each tab.
回答2:
Yes it is possible to show/hide elements in any view. You can access the tab bar controller to know which tab is selected via the tabBarController
property of your custom view controller.
来源:https://stackoverflow.com/questions/6682651/same-view-in-multiple-tabs