Reputation: 13286
I have looked at several Stackoverflow questions where people have problems with boundingRectWithSize, but none of them are quite my problem.
The following code often computes a height that is 1 line of text too tall.
CGFloat height = [label.attributedText
boundingRectWithSize:CGSizeMake(label.width, CGFLOAT_MAX)
options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading)
context:nil].size.height;
For example, the string Map Type: USGS Topo is about half the width of my view and should be 1-line tall (~18 pixels), but ends up having a 2-line height (~36 pixels):
I also tried calculating the height using the NSString instead of NSAttributedString, but the same thing happens:
CGFloat height = [[label.attributedText string]
boundingRectWithSize:CGSizeMake(label.width, CGFLOAT_MAX)
options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading)
attributes:@{NSFontAttributeName:TITLE_FONT}
context:nil].size.height;
You can see in this screenshot that the bottom 3 labels end up sized correctly, but not the top two. I turned on color blended labels in the iOS simulator so the subviews would be colored to illustrate:
Upvotes: 1
Views: 473
Reputation: 386018
You probably have a trailing newline in your string. Try trimming it with whitespaceAndNewlineCharacterSet
.
Upvotes: 3
Reputation: 5121
I have had something similar happen to me awhile ago, though it was not with an attributed string. When it happened to me the lable's frame wasn't fully set yet and so at the time of the calculation the width was narrow enough that it had to wrap to the next line. Check the frame for your label when you do this calculation and make sure it is actually as wide as you think it is.
Upvotes: 0