I wrote the following method to calculate the height of an NSAttributedString with a given width:
- (CGFloat)findHeightForText:(NSString *)text havingWidth:(CGFloat)widthValue {
CGFloat height = 0.0;
if (text) {
CGRect frame = [text boundingRectWithSize:CGSizeMake(widthValue, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin| NSStringDrawingUsesFontLeading attributes:@{ NSFontAttributeName : [UIFont systemFontOfSize:14 weight:UIFontWeightRegular] } context:nil];
height = ceil(frame.size.height);
}
return height;
}
In addition to color, the attribute label string only has a font attribute:
NSFontAttributeName : [UIFont systemFontOfSize:14 weight:UIFontWeightRegular]
The problem is that sometimes it returns an invalid value. For instance. I see that the text is laid out in three lines, however the height value that I get has two lines. In the same way, sometimes it returns a height value for two lines, while text can be laid out using one line.
I do not pass paragraph style because NSLineBreakByWordWrapping is the default.
I read similar topics, but none of them gave me a solution. What am I missing?
bp14 source
share