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;
I did this by completely replacing the title view. The end result looks like this:
It can be achieved with the following code in the
viewDidLoad
method.To do this I used the excellent KeepLayout library. It yields a result like this:
An alternative approach may be to use a prompt.
https://www.reddit.com/r/swift/comments/3izq7b/style_guidelines_for_navigation_bar_prompts/