I noticed that the titleView's position depends on the rightbarbutton title. How can I set the frame of the titleView to be in the center instead?
I've tried setting titleView.frame, but to no avail.
Here's the code:
UIButton *titleLabel = [UIButton buttonWithType:UIButtonTypeCustom];
[titleLabel setTitle:@"Right Eye" forState:UIControlStateNormal];
[titleLabel setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[titleLabel setTitleColor:[UIColor blackColor] forState:UIControlStateHighlighted];
titleLabel.frame = CGRectMake(100, 0, 180, 44);
titleLabel.titleLabel.backgroundColor = [UIColor clearColor];
titleLabel.titleLabel.font = [UIFont boldSystemFontOfSize:20.0];
titleLabel.titleLabel.shadowColor = [UIColor colorWithWhite:0.0 alpha:0.3];
// titleLabel.titleLabel.textAlignment = UITextAlignmentCenter; (this doesn't work either)
[titleLabel addTarget:self action:@selector(titleTap:) forControlEvents:UIControlEventTouchUpInside];
self.navigationItem.titleView = titleLabel;
self.navigationItem.titleView.frame = CGRectMake(100, 0, 180, 44); //(this doesn't work either)
I was implementing a two row title similar to something WhatsApp is doing (title and subtitle).
I fixed this problem by subclassing
UINavigationController
and overridingviewDidLayoutSubviews()
.My titleView looks like the following (in a
viewController
):My
viewDidLayoutSubviews()
:Note: The trick is to have a wrapper view around your titleView which can be layed out by the navigation bar. Then adjust the frame of your titleView to what you desire.
Just add invisible button (no text) on right side of navigation bar, and change it size to for example 20 px
After setting up your titleView or titleLabel, call
sizeToFit
on it, also make suretitleLabel.textAlignment = UITextAlignmentCenter
. It'll be centered in the width of the navbar rather than in the space between the button edge and far edge of navbar.You can try set the frame to CGRectZero initially and call sizeToFit. Below is the code I used to change the title text and made sure it is still centered. I had a back button on the left.
None of the suggestions here really worked for me. My issue was that I was setting titleView while the navigation bar was in the middle of it's transition - I'd get this weird jitter where the titleView would flicker over to the left, and then end up back in the center.
I ended up following smallduck's idea and overriding setFrame, was as simple as: