I want a titleView inside my UINavigationBar which has two lines of text instead of only one
My current implementiation works well when I have a "Back"-Button and an "Edit" Button because it looks nearly centered. The problem is when I only have one of the Buttons. It looks really weird and wrong because the view centers itself on the available space.
UINavigationBar with left and right Button
UINavigationBar with only one Button
This is my current implementation:
CGRect frame = self.navigationController.navigationBar.frame;
UIView *twoLineTitleView = [[UIView alloc] initWithFrame:CGRectMake(CGRectGetWidth(frame), 0, CGRectGetWidth(frame), CGRectGetHeight(frame))];
UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 8, CGRectGetWidth(frame), 14)];
titleLabel.backgroundColor = [UIColor clearColor];
titleLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
titleLabel.textAlignment = UITextAlignmentCenter;
titleLabel.text = self.title;
[twoLineTitleView addSubview:titleLabel];
UILabel *subTitleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 23, CGRectGetWidth(frame), 14)];
subTitleLabel.backgroundColor = [UIColor clearColor];
subTitleLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
subTitleLabel.textAlignment = UITextAlignmentCenter;
subTitleLabel.text = self.subTitle;
[twoLineTitleView addSubview:subTitleLabel];
self.navigationItem.titleView = twoLineTitleView;
Here is how I would do it:
This code should work for you:
Swift 3 variant:
You can also use an attributed string to achieve the same result:
Swift 3
Inspired by @Ben Smiley, I added a masonry implementation.
I was using Rodrigo Pedroso's answer, but the fact that it doesn't truncate long titles became a problem. I made a version that measures how much space there is for the title between the bar button items, and then manually truncates the title to fit in that space. The truncation code was adapted from this answer, and is a bit of a mess - maybe someone can help figure out a way to use UILabel's built-in truncation methods (i.e. .ByTruncatingTail). I've already spent too much time on this though.
Here's what I've got:
In addition to the github! here.
I found that when my subtitle was smaller than my Title it would not format it correctly here is the right code.
A few additions to Brian van den hovel's answer to better centralise title and subtitle.