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;
In my case I was trying to set it in a child view controller, this fixed it
self.parentViewController.navigationItem.titleView = titleView;
The view of the navigationItem is set, by default, to nil.
You need to use
self.navigationItem.titleView = btn;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With