Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't add UIBarButtonItem to independent UINavigationBar

I am programatically adding a UINavigationBar to a UIView, and now need to add a UIBarButtonItem to it. I am trying to use the following:

UIBarButtonItem *doneButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(dismissView)];
[header setItems:[NSArray arrayWithObjects:doneButton, nil] animated:NO];
[doneButton release];

My app crashes and I find this in the console:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UIBarButtonItem setNavigationBar:]: unrecognized selector sent to instance 0x4b75c00'

Would appreciate it if someone could please point out what am I doing incorrectly here.

Thanks. Ricky.

like image 577
Ricky D'Amelio Avatar asked Nov 22 '10 04:11

Ricky D'Amelio


2 Answers

UINavigationBar accepts an array of UINavigationItem objects, each of which contain properties about a given level of the navigation hierarchy. You probably want to create a new UINavigationItem and then set its rightBarButtonItem property to your Done button.

like image 138
Justin Spahr-Summers Avatar answered Nov 11 '22 17:11

Justin Spahr-Summers


It's unlikely you need to create a new UINavigationItem as the answer currently states. In contrast if you already have a UINavigationBar initialized from a nib which also contains a view, you can just add your UINavigationItem to the topItem property of your UINavigationBar. Something like this:

UIBarButtonItem *closeBtn = [[UIBarButtonItem alloc] initWithTitle:@"Close" 
                                                             style:UIBarButtonItemStyleBordered 
                                                            target:self 
                                                            action:@selector(closeBtnPressed)];
self.navigationBar.topItem.leftBarButtonItem = closeBtn;
[closeBtn release];
like image 30
wprater Avatar answered Nov 11 '22 18:11

wprater