Just had the same problem. Calculating a lot of sizes of UILabel
s or UITextView
s is expensive, so I wondered if there's a cheaper way than configuring a label or text view and then asking it for the size. This is especially important when calculating row heights for long table views.
Turns out, there is: UILabel seems to be built up UIKit's string additions for layout and drawing while UITextView uses Text Kit (in iOS 7). Both facilities can be configured to use the same settings and calculate string dimensions cheaper that using the UIKit classes.
For a UILabel here's what I found out:
CGFloat labelHeight = [testString boundingRectWithSize:(CGSize){ labelWidth, CGFLOAT_MAX }
options:NSStringDrawingUsesLineFragmentOrigin
attributes:@{ NSFontAttributeName : labelFont };
context:nil].size.height;
labelHeight = ceil(labelHeight);
This assumes numberOfLines = 0
. Note the need to round up the result.
I tested above code with about 4000 string rendered into 100 different widths and all results were equal to the UILabel I used for comparison.
I did the same to calculate dimensions of UITextView
which is more complicated and required to set up an NSLayoutManager
. Here the speedup is even more impressive (~ 50 times faster than using the UITextView).
If anybody's interested here's the code and test project.