Very simple question, I'm trying to dynamically get the height of a UILabel, and it seems the boundingRectWithSize:options:context:
is ignoring my second line. I've pasted the relevant code below:
CGSize maximumLabelSize = CGSizeMake(self.frame.size.width,CGFLOAT_MAX);
return [self.attributedText boundingRectWithSize:maximumLabelSize options:NSStringDrawingUsesLineFragmentOrigin context:nil].size;
I think I'm setting it up right, however this returns 17 (after getting the height and rounding up) regardless of whether it is 1 or 2 lines. Any help would be appreciated!
Edit: When using NSStringDrawingUsesFontLeading it cuts my second line off completely.
I hope this helps. It is a simple solution. It's needed to round up the expected height.
+ (void)adjust:(UILabel *)label withString:(NSString*)string withMaximumSize:(CGSize)maxSixe{
CGRect expectedLabelRect = [string boundingRectWithSize:maxSixe
options:NSStringDrawingUsesLineFragmentOrigin
attributes:@{NSFontAttributeName: label.font}
context:nil];
expectedLabelRect.size.height = ceilf(expectedLabelRect.size.height);
//adjust the label the the new height.
CGRect newFrame = label.frame;
newFrame.origin.y += (newFrame.size.height - expectedLabelRect.size.height) * 0.5;
newFrame.size.height = expectedLabelRect.size.height;
label.numberOfLines = ceilf(newFrame.size.height/label.font.lineHeight);
label.frame = newFrame;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.