Question

I'm trying to have two UILabels in my navigation bar instead of just one.

I followed this link to have informations on how to do that: iPhone Title and Subtitle in Navigation Bar

It works well, but I can't get my texts to be centered properly. It is centered between the buttons, but the default title behaviour is to center itself right under the time.

enter image description here

I had a look here, same question, but no answer: UINavigationBar TitleView with subtitle

What am I missing? Here is my code:

CGRect headerTitleSubtitleFrame = CGRectMake(0, 0, 200, 44);
UIView* _headerTitleSubtitleView = [[UILabel alloc] initWithFrame:headerTitleSubtitleFrame];
_headerTitleSubtitleView.backgroundColor = [UIColor clearColor];
_headerTitleSubtitleView.autoresizesSubviews = NO;

CGRect titleFrame = CGRectMake(0, 2, 200, 24);
UILabel *titleView = [[UILabel alloc] initWithFrame:titleFrame];
titleView.backgroundColor = [UIColor clearColor];
titleView.font = [UIFont boldSystemFontOfSize:20];
titleView.textAlignment = NSTextAlignmentCenter;
titleView.textColor = [UIColor whiteColor];
titleView.shadowColor = [UIColor darkGrayColor];
titleView.shadowOffset = CGSizeMake(0, -1);
titleView.text = @"Title";
titleView.adjustsFontSizeToFitWidth = YES;
[_headerTitleSubtitleView addSubview:titleView];

CGRect subtitleFrame = CGRectMake(0, 24, 200, 44-24);
UILabel *subtitleView = [[UILabel alloc] initWithFrame:subtitleFrame];
subtitleView.backgroundColor = [UIColor clearColor];
subtitleView.font = [UIFont boldSystemFontOfSize:13];
subtitleView.textAlignment = NSTextAlignmentCenter;
subtitleView.textColor = [UIColor whiteColor];
subtitleView.shadowColor = [UIColor darkGrayColor];
subtitleView.shadowOffset = CGSizeMake(0, -1);
subtitleView.text = @"Subtitle";
subtitleView.adjustsFontSizeToFitWidth = YES;
[_headerTitleSubtitleView addSubview:subtitleView];

self.navigationItem.titleView = _headerTitleSubtitleView;
Was it helpful?

Solution

You should adjust the width of both frames. It should be below 200. try this.

CGRect titleFrame = CGRectMake(0, 2, 160, 24);
CGRect subtitleFrame = CGRectMake(0, 24, 160, 44-24);

Edit : Your backbutton on the left is wider, and the titleview is shifted to the right.

Please look the image with width 200px enter image description here

And the image with width 160px enter image description here

I suggest you to adjust the width of titleview and label accordingly.

If you want to know more about backbutton width, then please refer the discussion here. SO Post 1.

SO Post 2.

OTHER TIPS

you may like this property in UINavigationItem class.

@property (nonatmic,copy) NSString *prompt

It's elegant.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top