Search code examples
iphoneiosuinavigationcontrolleruinavigationitem

UINavigationItem centering the title


I have a navigationBar with both Left and Right bar buttons on each side. I have a customTitlelabel which I set as the titleView of the UINavigationItem.

[self.navigationItem setTitleView:customTitleLabel];

All is fine now. The problem, the size of the rightbarButton is dynamic based on the input I get in one of the text fields.

Therefore the title is automatically centered based on the available space between the buttons.

how can i set the title to a fixed position?


Solution

  • You can't do what you want directly -- the position of your title view is out of your control (when managed by UINavigationBar).

    However, there are at least two strategies to get the effect you want:

    1) Add the title view not as the 'proper' title view of the nav bar, but as a subview of the UINavigationBar. (Note: this is not 'officially' sanctioned, but I've seen it done, and work. Obviously you have to watch out for your title label overwriting bits of the buttons, and handle different size nav bars for different orientations, etc. -- a bit fiddly.)

    2) Make an intelligent UIView subclass that displays a given subview (which would be your UILabel) at a position calculated to effectively show the subview perfectly centered on the screen. In order to do this, your intelligent UIView subclass would respond to layout events (or frame property changes etc.) by changing the position (frame) of the label subview.

    Personally, I like the idea of approach 2) the best.