Alex Wilson Alex Wilson - 1 month ago 7
iOS Question

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

I have multiline attributed text in a UILabel that I would like to find the width of. The purpose of this is to resize the font size for different devices. To do this I check whether the text with line breaks will fit a given space. I have tried

text.size.width
, however this will give the width as if the text is taking up one line.

Answer

Try this solution:

Here we get the size the entire NSAttributedString

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

You can then use it to find the width of the NSAttributedString Hope this helps you out.