如何在 UINavigationController 标题中的图块旁边添加图标?

How to add icon next to tile in UINavigationController title?

我正在尝试在导航栏标题旁边添加一个下拉箭头或图标(如下面的屏幕截图所示),但没有找到好的解决方案,我认为这会相当简单,但我只是无法得到一个好的解决方案。

我尝试的一种方法是通过设置视图控制器的 navigationItem.titleView 将标题替换为 UIButton,但这种方法的问题是因为我的标题长度可能会有所不同,所以我不能计算 CGRect 的按钮框架大小报告为 0,0。如果我尝试在 viewWillDisplay() 方法中更新按钮的框架,那么按钮框架的变化会在适当的位置放大动画,并且用户可以看到它,并且效果非常不和谐。

还有其他可能的解决方案吗,我觉得我只是在接近这个问题,这不应该这么难。

您可以设置带有属性字符串的标签,它会自动调整大小

短标题

长标题

例如

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;

如果您的字符在列表中作为 Unicode 字符可用,那么您可以将它添加到字符串中

按:Ctrl + Command + Space

假设您的角色是向下箭头,那么您可以将它添加到您的标题字符串中。

如果你想添加属性字符串或图标,那么你可以按照Leo的答案。

创建一个包含 UILabel 和 UIButton 的 UIView。

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;