繁体   English   中英

iOS - 使用归属文本自动缩小UILabel

[英]iOS - Auto-shrink UILabel with Attributed text

我有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;

我想这是你之前的问题的后续内容。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM