开发者

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.


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.


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];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜