Search code examples
iphoneobjective-ccocoa-touchipaduinavigationitem

UINavigationItem titleView position


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: the text isn't properly centered. I've tried setting the x origin of the label, but this has no effect.


Solution

  • 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!