Problem adding UIBarButtonItems to a ToolBar

别等时光非礼了梦想. 提交于 2019-12-03 11:21:50

Replace this line:

[[self navigationController] setToolbarItems:arr animated:YES];

with this:

[self setToolbarItems:arr animated:YES];

In general, you should set toolbarItems on each individual view controller that you push, and not on your UINavigationController itself.

I found out in the documentation of Apple there is small paragraph explaining the UIToolBar. In this paragraph there is a very tiny sentence stating: "[..] When displayed, this toolbar obtains its current set of items from the toolbarItems property of the active view controller [..]" But they don't explain that view first has to be active to obtain these buttons. So that means that the UIToolBar is ready to retrieve it's Buttons on viewDidAppear and NOT on viewDidLoad message.

- (void)viewDidAppear:(BOOL)animated {
    [[self tableView] reloadData];

    [[self navigationController] setToolbarHidden: NO animated:YES];    
    UIBarButtonItem * logoutButton = [[[UIBarButtonItem alloc] initWithTitle:@"Log out" style:UIBarButtonItemStylePlain target:self action:@selector(logOut:)]autorelease];
    NSMutableArray * arr = [NSMutableArray arrayWithObjects:logoutButton, nil];
    [self setToolbarItems:arr animated:YES];

    [super viewDidAppear:animated];
}

Maybe you can use interface builder to avoid this, however it will be slower

http://developer.apple.com/iphone/library/documentation/UIKit/Reference/UINavigationController_Class/Reference/Reference.html

"The navigation controller object now manages an optional toolbar in its view hierarchy. When displayed, this toolbar obtains its current set of items from the toolbarItems property of the active view controller."

Have you tried subclassing UITableViewController for your tableview and setting up with the appropriate toolbarItems property?

I've made a view controller, which is a subclass of UITableViewController, and I've got the toolbar working by doing the following:

In viewDidLoad:

self.navigationController.toolbar.barStyle = UIBarStyleBlackTranslucent;

NSArray* toolbarItems = [NSArray arrayWithObjects: button1,
                                                   button2,
                                                   button3,
                                                   nil];

[self setToolbarItems:toolbarItems animated:NO];

Then, because I want the toolbar only on this screen, I added this to viewWillAppear:

[self.navigationController setToolbarHidden:NO animated:YES];

And finally, I hide the toolbar again in viewWillDisappear:

[self.navigationController setToolbarHidden:YES animated:YES];

This works for me with "text" buttons, built in icons and custom icons.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!