Toolbar in Navigation Controller

2019-03-31 09:23发布

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

2条回答
来,给爷笑一个
2楼-- · 2019-03-31 09:32

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];
}
查看更多
Bombasti
3楼-- · 2019-03-31 09:37

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];
}
查看更多
登录 后发表回答