UINavigationBarItem programmatically

2019-09-06 10:30发布

问题:

I have view controller which is inherited from UINavigationController. On viewDidLoad I want to set rightBarButtonItem. I do following.

UINavigationItem* navItem = self.navigationItem;
UIButton* btnOptionsView = [[UIButton alloc] init];
[btnOptionsView setImage:[UIImage imageNamed:@"options.png"]
                forState:UIControlStateNormal];
[btnOptionsView sizeToFit];
UIBarButtonItem* btnOptions = [[UIBarButtonItem alloc] initWithCustomView:btnOptionsView];
navItem.rightBarButtonItem = btnOptions;

but the button is invisible, in debug mode I have noticed that btnOptions.width is 0, and also I can't set the title for navItem, something like this

[navItem setTitle:@"title"]

does not change the title of UINavigationItem.

回答1:

You should not subclassing UINavigationController. From apple documentation:

The UINavigationController class implements a specialized view controller that manages the navigation of hierarchical content. This class is not intended for subclassing. Instead, you use instances of it as-is in situations where you want your application’s user interface to reflect the hierarchical nature of your content.



回答2:

try to change the title of the button