Adjusting navigationItem.titleView's frame?

Sometime in between your view controller's viewWillAppear: & viewDidAppear:, the navigation bar is repositioning your titleView and resizing it to fit if necessary. It can end up uncentered because the navigation bar is prefering not to resize your titleView to fit between the buttons. It seems to try to center the title view if it's small enough, but if not will move your titleView off-center, and then I think only as last resort will resize. The effect is that the titleView is taking up all the space between the two buttons, if its textAlignment is centered then it will centered in that space though not the centered with respect to the whole screen. You can see this in your screen shot.

One answer is to make your titleView narrower so the navigation bar can center it, so try about 160 instead of 180 when you set your titleView.frame. It sucks that, when creating the view programmatically like you are, one has to put an estimate for that width into the code. What would be good is a way to maximize that space while staying centered.

It's possible to start with the titleView being the screen width, then after the navigation bar changes titleView.frame, update it again yourself in the view controller's viewDidAppear:. Using its adjusted titleView.frame.origin.x and size.width along with the screen width, you can calculate the largest of the left & right margins, then set the origin.x to that, the size.width to the screen width minus that times 2. However that doesn't take effect until after the pushed view has animated in and the shift afterwards is visible. You could hide the titleView in viewWillAppear: then unhide in viewDidAppear: after centering it, so instead of sliding in with an off-center titleView which is then shifted, it would slide in with no title which then appears.

A better possibility is to make your titleView your own subclass of UIView (or UILabel or whichever) and override setFrame to resize itself to stay centered in its superview. If I ever end up doing this myself I'll post it here. Or maybe someone else knows another place to change the titleView's frame after its been updated but before the view slides in without a view subclass.


After setting up your titleView or titleLabel, call sizeToFit on it, also make sure titleLabel.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.


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:

- (void)setFrame:(CGRect)frame {
    [super setFrame:CGRectMake(0, 0, self.superview.bounds.size.width, self.superview.bounds.size.height)];
}