非常简单的问题,我试图动态获取UILabel的高度,似乎boundingRectWithSize:options:context:
忽略了我的第二行。我已粘贴以下相关代码:
CGSize maximumLabelSize = CGSizeMake(self.frame.size.width,CGFLOAT_MAX);
return [self.attributedText boundingRectWithSize:maximumLabelSize options:NSStringDrawingUsesLineFragmentOrigin context:nil].size;
我认为我正确设置它,但无论是1行还是2行,它都会返回17(在获得高度和向上舍入后)。任何帮助将不胜感激!
编辑:当使用NSStringDrawingUsesFontLeading时,它会完全切断我的第二行。
答案 0 :(得分:-1)
我希望这会有所帮助。这是一个简单的解决方案。需要将预期高度向上舍入。
+ (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;
}