boundingRectWithSize for NSAttributedString returning wrong size

RunLoop picture RunLoop · Nov 29, 2012 · Viewed 125.9k times · Source

I am trying to get the rect for an attributed string, but the boundingRectWithSize call is not respecting the size I pass in and is returning a rect with a single line height as opposed to a large height (it is a long string). I have experimented by passing in a very large value for the height and also 0 as in the code below, but the rect returned is always the same.

CGRect paragraphRect = [attributedText boundingRectWithSize:CGSizeMake(300,0.0)
  options:NSStringDrawingUsesDeviceMetrics
  context:nil];

Is this broken, or do I need to do something else to have it returned a rect for wrapped text?

Answer

Ed McManus picture Ed McManus · Mar 14, 2013

Looks like you weren't providing the correct options. For wrapping labels, provide at least:

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

Note: if the original text width is under 300.f there won't be line wrapping, so make sure the bound size is correct, otherwise you will still get wrong results.