Suppose I have a container controller that accepts an array of UIViewControllers and lays them out so the user can swipe left and right to transition between them. This container controller is wrapped inside a navigation controller and is made the root view controller of the application's main window.
Each child controller makes a request to the API and loads a list of items that are displayed in a table view. Based on the items that are displayed a button may be added to the navigation bar that allows the user to act on all the items in the table view.
Because UINavigationController only uses the UINavigationItems of its child view controllers, the container controller needs to update its UINavigationItem to be in sync with the UINavigationItem of its children.
There appear to be two scenarios that the container controller needs to handle:
- The selected view controller of the container controller changes and therefore the UINavigationItem of the container controller should update itself to mimic the UINavigationItem of the selected view controller.
- A child controller updates its UINavigationItem and the container controller must be made aware of the change and update its UINavigationItem to match.
The best solutions I've come up with are:
- In the setSelectedViewController: method query the navigation item of the selected view controller and update the leftBarButtonItems, rightBarButtonItems and title properties of the container controller's UINavigationItem to be the same as the selected view controller's UINavigationItem.
- In the setSelectedViewController method KVO onto the leftBarButtonItems, rightBarButtonItems and title property of the selected view controller's UINavigationItem and whenever one of those properties changes up the container controller's UINavigationItem.
This is a recurring problem with many of the container controllers that I have written and I can't seem to find any documented solutions to these problems.
What are some solutions people have found to this problem?
- (UINavigationItem *) navigationItem
and justreturn selectedViewController.navigationItem;
? – Aaron Brager+ (NSSet *)keyPathsForValuesAffectingNavigationItem { return [NSSet setWithObjects:@"selectedViewController", nil]; }
. That will trigger KVO on navigationItem any time the selectedViewController property changes. I'm not sure ifUINavigationController
is observingnavigationItem
with KVO though. – Aaron Brager