iOS - 自动调整带属性文本的UILabel大小

11

我有一个包含两个带属性的字符串的 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,并在属性检查器中的“自动收缩”下拉菜单中配置了“最小字体大小”。 - Mick MacCallum
1个回答

6

我猜这是你之前的问题的继续。

我认为你不能自动完成这个任务,但是有一个size方法可用于检查字符串是否过长,如果需要可以进行调整。


是的,最终我使用了两个单独的明文 UILabel。 - Oleg

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接