[英]Attributed Text boundingRectWithSize returning wrong size
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. 非常简单的问题,我正在尝试动态获取UILabel的高度,似乎boundingRectWithSize:options:context:
忽略了我的第二行。 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. 我认为我正确设置它,但无论是1行还是2行,它都会返回17(在获得高度和四舍五入之后)。 Any help would be appreciated! 任何帮助,将不胜感激!
Edit: When using NSStringDrawingUsesFontLeading it cuts my second line off completely. 编辑:当使用NSStringDrawingUsesFontLeading时,它完全切断我的第二行。
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.