Toolbar in Navigation Controller

2019-03-31 08:58发布

问题:

I am creating a toolbar in a Navigation Controller using the following code:

 [self.navigationController setToolbarHidden:NO];

 //Create a button
     NSArray *toolbarItems = [NSArray arrayWithObjects:
                              [[UIBarButtonItem alloc] initWithTitle:@"Help" style:UIBarButtonItemStyleBordered target:self action:@selector(helpButton:)]
                              ,nil];

The only problem is that the toolbar is visible whenever there is a navigation controller(multiple other views). Is there a way to only restrict the toolbar to a single view?

Thanks

回答1:

To quote the UINavigationController Class Reference:

The navigation toolbar is hidden by default but you can show it for your navigation interface by calling the setToolbarHidden:animated: method of your navigation controller object. If not all of your view controllers support toolbar items, your delegate object can call this method to toggle the visibility of the toolbar during subsequent push and pop operations.

So, set a delegate for your navigation controller. In your delegate's navigationController:willShowViewController:animated:, do something like this:

- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated
{
    BOOL shouldShowToolbar = (viewController == theViewControllerThatNeedsAToolbar);
    [navigationController setToolbarHidden:shouldShowToolbar animated:animated];
}


回答2:

If you slightly modify the above example you can easily make it so the toolbar will automatically show when toolbar items are set in the current view controller's viewDidLoad method:

- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated
{
    BOOL shouldHide = [viewController.toolbarItems count] == 0;
    [navigationController setToolbarHidden:shouldHide animated:animated];
}