【问题标题】:How to add icon next to tile in UINavigationController title?如何在 UINavigationController 标题中的磁贴旁边添加图标?
【发布时间】:2015-09-23 01:21:02
【问题描述】:

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

我尝试的一种方法是通过设置视图控制器的navigationItem.titleView 将标题替换为UIButton,但这种方法的问题是因为我的标题长度可能不同我无法计算按钮框架大小@ 987654325@ 报告为 0,0。如果我尝试在 viewWillDisplay() 方法中更新按钮的框架,那么按钮框架的变化会在原地放大动画,并且对用户来说是可见的,而且效果非常不和谐。

还有其他可能的解决方案吗,我觉得我只是在处理这一切都错了,应该不会这么难。

【问题讨论】:

标签: ios objective-c ios7 uinavigationcontroller uinavigationbar


【解决方案1】:

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

按:Ctrl + Command + Space

假设你的角色是DOWN ARROWHEAD,那么你可以将它添加到你的标题字符串中。

如果您想添加属性字符串或图标,则可以关注Leo 的回答。

【讨论】:

  • 酷,这是一个非常简单的解决方案,只要 unicode 字符与标签的字体很好地对齐。我之前尝试过,但不喜欢 unicode 图标。
【解决方案2】:

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

短标题

长标题

例如

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;

【讨论】:

  • 你知道是否可以通过设置 CATransform3DMakeRotation 等来为图标图像更改设置动画?我希望标签上的点击手势将向下 V 形旋转到向上 V 形。
  • 您是如何找到 0,0,100,40 的标签框 rect 的?如果您不知道尺寸怎么办?
【解决方案3】:

创建一个包含 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;

【讨论】:

  • 这不起作用,因为 label.frame.size 在 vi​​ewWillDisplay() 之前为 0,0
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-02-05
  • 1970-01-01
  • 2017-04-11
  • 1970-01-01
  • 2012-05-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多