美文网首页iOS
iOS 使用 boundingRectWithSize:计算文字

iOS 使用 boundingRectWithSize:计算文字

作者: 梦里挑灯看键 | 来源:发表于2017-01-16 10:53 被阅读1295次

在平时的项目开发中,我们经常会遇到文字多行显示的问题,经常我们使用的方法是: 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,因为一个中文标点符号站的是两个字符。可能存在显示是按两行显示但高度结算确只有一行的高度,就会导致计算不正确。我们可以使用LabelsizeThatFits方法:

+ (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;
}

相关文章

网友评论

    本文标题:iOS 使用 boundingRectWithSize:计算文字

    本文链接:https://www.haomeiwen.com/subject/uonubttx.html