【问题标题】:iOS - Auto-shrink UILabel with Attributed textiOS - 使用属性文本自动收缩 UILabel
【发布时间】:2013-01-25 17:59:18
【问题描述】:

我有UILabel,其中包含两个由新行分隔的属性字符串。 第一个字符串的字体大小设置为 17,第二个字符串的字体大小设置为 14。 如果我的第一个 NSMutableAttributedString 的内容不能放在一行中,我希望将其调整为最小字体大小。

这可能吗?

通过在 IB 中为纯文本设置“自动缩小到最小字体大小”来配置 UILabel 行为非常简单,但不知道如何为属性文本执行此操作。

这是我的代码:

NSString *eventName = @"Looong Event Name";
NSString *placeString = @"My place";

eventName = [eventName stringByAppendingString:@"\n"];        
NSMutableAttributedString *attrName = [[NSMutableAttributedString alloc] initWithString:eventName];
[attrName addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:17] range:NSMakeRange(0, [eventName length])];


 NSMutableAttributedString *attrPlace = [[NSMutableAttributedString alloc] initWithString:placeString];
 [attrPlace addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:14] range:NSMakeRange(0, placeString.length)];
 [attrPlace addAttribute:NSForegroundColorAttributeName value:[UIColor grayColor] range:NSMakeRange(0, placeString.length)];

  NSMutableAttributedString *finalString = [[NSMutableAttributedString alloc] initWithAttributedString:attrName];
  [finalString appendAttributedString:attrPlace];

  UILabel *nameLabel = (UILabel *)[cell viewWithTag:100];

  nameLabel.attributedText = finalString;

【问题讨论】:

  • 当我尝试这样做时,这变得相当头疼。我不会将此作为答案发布,因为很可能存在我无法找到的更好的解决方案。但是,我最终以编程方式配置了所有字符串的属性(除了那些与大小有关的属性)并将标签设置为 IBOutlet,并在属性检查器的“自动收缩”下拉菜单中配置了“最小字体大小”。

标签: iphone ios xcode cocoa-touch nsattributedstring


【解决方案1】:

我猜这是你的earlier question 的后续。

我认为您不能自动执行此操作,但是 NSAttributedString 有一个 size 方法,您可以使用它来检查您的字符串是否太大,并在需要时自行调整。

【讨论】:

  • 是的,我最终使用了两个单独的纯文本 UILabel。
猜你喜欢
  • 1970-01-01
  • 2014-02-11
  • 2014-10-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多