我有一个包含两个带属性的字符串的 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;