Evgeniy Kleban Evgeniy Kleban - 2 months ago 18
iOS Question

Right bar button does not appear

I try to add UINavigationBar programmatically and set bar button items.
I tried:

self.artificialNavBar = [[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 44)];
self.artificialNavBar.backgroundColor = [UIColor whiteColor];
UIBarButtonItem *bbiDone = [[UIBarButtonItem alloc] initWithTitle:@"Готово" style:UIBarButtonItemStyleDone target:nil action:nil];
UIBarButtonItem *bbiTry = [[UIBarButtonItem alloc] initWithTitle:@"Cancel" style:UIBarButtonItemStyleDone target:nil action:nil];
UINavigationItem *navItem = [[UINavigationItem alloc] init];

navItem.leftBarButtonItem = bbiDone;
navItem.rightBarButtonItem = bbiTry;

self.artificialNavBar.items = @[ navItem ];
[self.view addSubview:self.artificialNavBar];


However, only left bar button appears, right one is hidden. Did i miss something?

Answer

Declare

@property (nonatomic, strong) UINavigationItem *navItem;

in the .h file of this class where you have written all these and then replace your code with below code.

self.artificialNavBar = [[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 44)];
self.artificialNavBar.backgroundColor = [UIColor whiteColor];
[self.view addSubview:self.artificialNavBar];

UIBarButtonItem *bbiDone = [[UIBarButtonItem alloc] initWithTitle:@"Готово" style:UIBarButtonItemStyleDone target:nil action:nil];
UIBarButtonItem *bbiTry = [[UIBarButtonItem alloc] initWithTitle:@"Cancel" style:UIBarButtonItemStyleDone target:nil action:nil];

self.navItem = [[UINavigationItem alloc] init];
[self.navItem setLeftBarButtonItem:bbiDone animated:NO]
[self.navItem setRightBarButtonItem:bbiTry animated:NO]

[self.artificialNavBar setItems:@[self.navItem] animated:NO]

and make sure the navbar is nonatomic and strong.

Comments