当文本有多行时,在 UILabel 中查找属性文本的宽度

Find width of attributed text in a UILabel when the text has multiple lines

我在 UILabel 中有多行属性文本,我想找到它的宽度。这样做的目的是调整不同设备的字体大小。为此,我检查带换行符的文本是否适合给定的 space。我试过 text.size.width,但是这会给出宽度,就好像文本占用了一行一样。

试试这个解决方案:

这里我们得到整个NSAttributedString

的大小
 CGRect paragraphRect =
      [attributedText boundingRectWithSize:CGSizeMake(300.f, CGFLOAT_MAX)
      options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading)
      context:nil];

然后您可以使用它来查找 NSAttributedString 的宽度 希望这对你有所帮助。