How to add bar button to uinavigationbar in iphone

2019-09-06 17:54发布

问题:

My class is a normal view controller and I added a navigation bar through IB and i am adding a barbutton item on left to the navigation bar programmatically using the following code

UIBarButtonItem *addButton1 = [[UIBarButtonItem alloc] initWithTitle:@"Start" style:UIBarButtonItemStylePlain target:self  action:@selector(tourBtnClicked:)];
 self.navigationItem.leftBarButtonItem = addButton1;       

but its not working... should i add the navigationbar also programmatically or should my class a uinavigationcontroller

Thank u

回答1:

If you're not using a UINavigationController, you will need to add code to manage the navigation bar programmatically. For example, you'd need to send a message to the navigation bar to push a navigation item onto its stack using the following method:

- (void)pushNavigationItem:(UINavigationItem *)item animated:(BOOL)animated

You should also make sure the the navigationItem property isn't currently nil when you attempt to set its properties. From the UIViewController class reference for the navigationItem property:

To ensure the navigation item is configured, you can override this property and add code to load the bar button items there or load the items in your view controller’s initialization code