newbie newbie - 1 year ago 83
iOS Question

How to add icon next to tile in UINavigationController title?

I'm trying to add a drop down arrow or an icon next to the title of navigation bar (shown in screenshot below) but haven't found a good solution, I thought it would be fairly straight forward but I just can't get a good solution going.

One approach I tried is to replace the title with a

by setting the view controller's
but the problem with this approach is since my title can vary in length I can't the button frame size calculated the
is reported as 0,0. If I try to update the button's frame in
method then the button frame change is zoomed in animated in place and it's visible to the user and quite a jarring effect.

Are there any other possible solutions, I feel like I'm just approaching this all wrong, it shouldn't be this hard.

Nav bar with arrow

Leo Leo
Answer Source

You can set a label with attributedstring,it will auto resize

Short title

enter image description here

Long title

enter image description here

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;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download