How do I add an icon next to the tile in the UINavigationController title?
I'm trying to add a down arrow or an icon next to the title of the navigation bar (shown in the screenshot below) but didn't find a good solution, I thought it would be pretty straight forward, but I just can "Get a good solution.
One of my approaches is to replace the title with UIButton
by setting a view controller navigationItem.titleView
, but the problem with this approach is that my title can vary in length. I can't seem to figure out the frame size of the button CGRect
reported as 0.0. If I try to update the border of the button in the method viewWillDisplay()
, then the change to the border of the button is animated and is visible to the user and has a rather dramatic effect.
Are there any other possible solutions, I feel like I'm just getting close to all of this, it shouldn't be that hard.
You can set a label with an attributed string, it will automatically resize
Short name
Long title
for example
UILabel * label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0,100, 40)];
label.textAlignment = NSTextAlignmentCenter;
label.autoresizingMask = UIViewAutoresizingFlexibleWidth;
NSTextAttachment * attach = [[NSTextAttachment alloc] init];
attach.image = [UIImage imageNamed:@"memoAccess"];
attach.bounds = CGRectMake(0, 0, 20, 20);
NSAttributedString * imageStr = [NSAttributedString attributedStringWithAttachment:attach];
NSMutableAttributedString * mutableAttriStr = [[NSMutableAttributedString alloc] initWithString:@"Title"];
[mutableAttriStr appendAttributedString:imageStr];
label.attributedText = mutableAttriStr;
self.navigationItem.titleView = label;
If your character is available as a Unicode character in the list, you can add it to the string
Press: Ctrl + Command + Space
Assuming your character is DOWN ARROWHEAD, you can add it to your title bar.
If you want to add Attributed String or Icon, you can follow Leo's answer.
UIView creation contains UILabel and UIButton.
UIView * container = [[UIView alloc]initWithFrame:CGRectZero];
container.backgroundColor = [UIColor clearColor];
// title text
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 10, 40)];
label.backgroundColor = [UIColor clearColor];
label.text = @"hello world";
label.textColor = [UIColor blackColor];
label.textAlignment = NSTextAlignmentCenter;
label.adjustsFontSizeToFitWidth = YES;
label.lineBreakMode = NSLineBreakByClipping;
label.numberOfLines = 1;
[label sizeToFit];
// button
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = CGRectMake(label.frame.origin.x, label.frame.size.width, 20, 40);
// resize container
container.frame = CGRectMake(0, 0, label.frame.size.width + button.frame.size.width, 40);
[container addSubview:label];
[container addSubview:button];
self.navigationItem.titleView = container;