简体   繁体   中英

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

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;

在我的情况下,我试图在子视图控制器中设置它,这解决了它

self.parentViewController.navigationItem.titleView = titleView;

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

You need to use

self.navigationItem.titleView = btn;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM