在平时的项目开发中,我们经常会遇到文字多行显示的问题,经常我们使用的方法是: boundingRectWithSize:
具体代码:
+ (CGSize)boundingRectWithSize:(CGSize)size font:(CGFloat)font text:(NSString *)text
{
NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
[style setLineBreakMode:NSLineBreakByCharWrapping];
style.alignment = NSTextAlignmentLeft;
NSDictionary *attribute = @{ NSFontAttributeName : FONT_SYSTEM(font), NSParagraphStyleAttributeName : style };
text = [[text componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"\r"]] componentsJoinedByString:@""];
CGSize retSize = [text boundingRectWithSize:size
options:
NSStringDrawingUsesLineFragmentOrigin |
NSStringDrawingUsesFontLeading|NSStringDrawingTruncatesLastVisibleLine
attributes:attribute
context:nil].size;
return retSize;
}
这个方法在中文情况下有时可能会出现bug,因为一个中文标点符号站的是两个字符。可能存在显示是按两行显示但高度结算确只有一行的高度,就会导致计算不正确。我们可以使用Label
的sizeThatFits
方法:
+ (CGSize)boundingRectWithSize:(CGSize)size font:(CGFloat)font text:(NSString *)text
{
if (![UTUtility shareInstance].hightLabel) {
[UTUtility shareInstance].hightLabel = [[UILabel alloc] init];
[UTUtility shareInstance].hightLabel.numberOfLines = 0;
}
[UTUtility shareInstance].hightLabel.font = FONT_SYSTEM(font);
[UTUtility shareInstance].hightLabel.text = text;
CGSize retSize = [[UTUtility shareInstance].hightLabel sizeThatFits:size];
return retSize;
}
网友评论