Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't the navigationItem.titleView working?

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];
like image 601
BlueDolphin Avatar asked Dec 05 '08 04:12

BlueDolphin


3 Answers

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;
like image 151
wisequark Avatar answered Nov 15 '22 18:11

wisequark


In my case I was trying to set it in a child view controller, this fixed it

self.parentViewController.navigationItem.titleView = titleView;
like image 43
Robert Avatar answered Nov 15 '22 18:11

Robert


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

You need to use

self.navigationItem.titleView = btn;
like image 25
August Avatar answered Nov 15 '22 17:11

August