简体   繁体   中英

Adding buttons to custom navigation bar

In my viewDidLoad method I have the following:

navigBar = [[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Back" style:UIBarButtonSystemItemAction target:self action:@selector(btnClicked:)];
[self.view addSubview:navigBar];

The button does not show up at all! What am I missing?

// create the navigation bar and add it to the view
UINavigationBar *navigationBar = [[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
[self.view addSubview:navigationBar];

// create a button
UIBarButtonItem *button = [[UIBarButtonItem alloc] initWithTitle:@"Back" style:UIBarButtonSystemItemAction target:self action:@selector(btnClicked:)];

// create a UINavigationItem and add the button in the right hand side
UINavigationItem *navItem = [[UINavigationItem alloc] initWithTitle:nil];
navItem.rightBarButtonItem = button;

// add the UINavigationItem to the navigation bar
[navigationBar pushNavigationItem:navItem animated:NO];

set button on navigation bar .then u create a BarButtonItem on navigation.

barbutton=[UIBarButtonItem alloc] ]initWithTitle......
navigation.navigationController.rightBarButton= barbutton;

First read this :

When you use a navigation bar as a standalone object, you are responsible for providing its contents. Unlike other types of views, you do not add subviews to a navigation bar directly. Instead, you use a navigation item (an instance of the UINavigationItem class) to specify what buttons or custom views you want displayed. A navigation item has properties for specifying views on the left, right, and center of the navigation bar and for specifying a custom prompt string.

A navigation bar manages a stack of UINavigationItem objects. Although the stack is there mostly to support navigation controllers, you can use it as well to implement your own custom navigation interface. The topmost item in the stack represents the navigation item whose contents are currently displayed by the navigation bar. You push new navigation items onto the stack using the pushNavigationItem:animated: method and pop items off the stack using the popNavigationItemAnimated: method. Both of these changes can be animated for the benefit of the user.

So basically what you need to do is :

[navigBar pushNavigationItem:self.navigationItem animated:NO];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM