Reputation: 6940
I know there is similar topics, but unfortunately their solution not work as i want. I have a label, with specific font, with constraints from left side equal to 16, and from right side equal to 16 also. So, for calculate expected text height i used this:
CGSize labelSize = [[strMod fineHtmlFromString:mdl.content] sizeWithFont:self.contentLabel.font
constrainedToSize:CGSizeMake(SCREEN_WIDTH - 32, (FLT_MAX))
lineBreakMode:NSLineBreakByWordWrapping];
self.heightFullSizeLabel = labelSize.height;
32 is a number, that is easily calculated as 16+16 (constraints indent). SCREEN_WIDTH is defined as #define SCREEN_WIDTH [[UIScreen mainScreen] bounds].size.width
Unfortunately, with that logic i get lesser height that i want to, so i had to increase 32 number to 40. Is there a way to precisely calculate label height dynamically with layout?
Upvotes: 0
Views: 99
Reputation: 26385
The correct way to know a text container size is to use -sizeToFit
or -sizeThatFits:(CGSize)size
.
The one you are using asks just the area occupied by a text, but it doesn't take into account padding or other view related stuff that can be applied.
You can see a huge difference in calculation if you use a UItexView that contains a lot of padding on each side
Upvotes: 1
Reputation: 598
Try this with your label font.
CGRect textRect = [text boundingRectWithSize:size
options:NSStringDrawingUsesLineFragmentOrigin
attributes:@{NSFontAttributeName:FONT}
context:nil];
CGSize size = textRect.size;
self.heightFullSizeLabel = size.height;
Upvotes: 1