UINavigationBar right button not showing up

安稳与你 提交于 2019-12-23 10:17:15

问题


I am using the following function via a notification to load a right button on my UINavigationBar, and even though I can trace out the button and verify it is allocated, it does not show up...any ideas?

EDIT 4/6/2011, 2:42PM

So, something interesting...the width always reports as 0.0...

- (void)showRightBarButton:(id)sender
{
    NSLog(@"Showing button");
    UIBarButtonItem *button = [[UIBarButtonItem alloc]
                               initWithBarButtonSystemItem:UIBarButtonSystemItemAdd
                               target:self
                               action:@selector(showPI:)];
    [button setTitle:@"This Button"];
    self.navigationItem.rightBarButtonItem = button;
    //[[self.navigationItem rightBarButtonItem] setWidth:50];
    NSLog(@"Button width is %f.", self.navigationItem.rightBarButtonItem.width);
    [button release];
}

回答1:


[self.view setNeedsDisplay];

You're right. That line isn't needed. As far as the rest of the code goes I don't see what's wrong with it. The only thing I've come up with so far is that self isn't the currently displayed view controller or that you're missing a navigation controller. Perhaps you've created your UINavigationBar yourself instead of using a navigation controller?

Anyway, for easier debugging I would suggest the following:

- (void)showRightBarButton:(id)sender
{
    NSLog(@"Showing button");
    UIBarButtonItem *button = [[UIBarButtonItem alloc]
                             initWithBarButtonSystemItem:UIBarButtonSystemItemAdd
                                                  target:self
                                                  action:@selector(showPI:)];
    self.navigationItem.rightBarButtonItem = button;
    [button release];
}

EDIT: The width isn't interesting. It's always 0.0 unless you specify it yourself.

The problem is that you're adding the button in the wrong place. You're not supposed to add the button to the navigation item of the navigation controller, but to the navigation item of the controller that is currently displayed by the navigation controller.




回答2:


You say you're using an NSNotification to trigger the addition of the bar button item. Where are you registering for the notification? Is it possible that the notification is being received before your view is loaded?

If you're registering for notifications in -init you may want to set a flag on your view controller that you should be displaying the bar button item and then reference that flag in -viewDidLoad to optionally display it.

Or you could just register for the notification in -viewDidLoad.



来源:https://stackoverflow.com/questions/5569965/uinavigationbar-right-button-not-showing-up

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