views:

5008

answers:

3

I'd like to put in an UIButton in the center of the navigation bar. Based on the document, it appears I need to set title view, and make sure the leftBarButtonItem is nil. But it is not work for me. Here is the code.

UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[btn setTitle:@"List" forState:UIControlStateNormal];
self.navigationItem.leftBarButtonItem = nil;
[self.navigationItem.titleView addSubview:btn];
+4  A: 

The view of the navigationItem is set, by default, to nil.

You need to use

self.navigationItem.titleView = btn;
August
A: 

Hmm, I have tried that way, but not working also.

BlueDolphin
Are you sure your UINavigationBar is using your UINavigationItem? Are you able to set the left and rightBarButtonItems?
Ben Gottlieb
Yes, I can set the rightBarButtonItem, and can see the result.
BlueDolphin
This should be a comment
Casebash
+5  A: 

If you examine your button, you'll find that by using the convenience method to initialize it you are left with a 0x0 button that is positioned at 0,0 within the bounds of the view it is being added to. Before doing this, you must define the contents of the frame property of the button. See the code below:

UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
btn.frame = CGRectMake(0, 0, 400, kCustomButtonHeight);
[btn setTitle:@"list" forState:UIControlStateNormal];
self.navigationItem.titleView = btn;
wisequark
It works, thanks!
BlueDolphin