I'm using UINavigationItem's titleView property to set a custom UILabel with my desired font size/color. Here's my code:
self.headerLabel = [[UILabel alloc] initWithFrame:CGRectMake(0.0, 0.0, 400.0, 44.0)];
self.headerLabel.textAlignment = UITextAlignmentCenter;
self.headerLabel.backgroundColor = [UIColor clearColor];
self.headerLabel.font = [UIFont boldSystemFontOfSize:20.0];
self.headerLabel.textColor = [UIColor colorWithRed:0.259 green:0.280 blue:0.312 alpha:1.0];
self.navigationItem.titleView = self.headerLabel;
In the navigation bar I also have a left bar button. The result is this:
alt text http://cl.ly/41164eec656c96e7c913/content
As you can see, the text isn't properly centered. I've tried setting the x origin of the label, but this has no effect.
I have a same problem; I just somehow solved this issue by calculating the title length and set the label frame width accordingly. Although this is not a perfect one but can be manageable. Here is the code.
I've used custom title labels for my nav bars in every app I have in the app store. I've tested many different ways of doing so and by far the easiest way to use a custom label in a navigation bar is to completely ignore
titleView
and insert your label directly intonavigationController.view
.With this approach, it's easy to have the title label's frame always match the navigationBar's frame -- even if you are using a custom navBar with a non-standard size.
The one caveat to this approach is that your title can flow over the top of any buttons you have in the navBar if you aren't careful and set the title to be too long. But, IMO, that is a lot less problematical to deal with than 1) The title not centering correctly when you have a rightBarButton or 2) The title not appearing if you have a leftBarButton.
If you make the headerLabel a subview of the titleView, you can then set headerLabel's frame to control where it goes within the titleView.
The way you are doing it now, you don't have that control. I think the OS chooses the titleView's frame for you based on the space available.
Hope this helps!
What worked for me was to update the titleView frame in the viewDidAppear method.
In stead of
initWithFrame
just useinit
and put[self.headerLabel sizeToFit]
after your last line of code.