动态计算字符串的区域大小

在一些列表中,可能需要根据文字的多少来动态调整Cell的高度,这就需要动态计算字符串的区域大小,IOS7以后可以使用以下方法

/**
 @method 得到指定字符串的区域大小
 @param str 要计算的字符串
 @param font 字体的大小
 @param width 限制字符串的显示宽度
 @result CGSize 计算后区域大小
 */
+ (CGSize)getSizeWithString:(NSString *)str withFont:(UIFont *)font withWidth:(CGFloat)width{
    NSStringDrawingOptions opts = NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading;
    NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
    [style setLineBreakMode:NSLineBreakByCharWrapping];
    NSDictionary *dic = @{NSFontAttributeName:font, NSParagraphStyleAttributeName:style};
    return [str boundingRectWithSize:CGSizeMake(width, MAXFLOAT) options:opts attributes:dic context:nil].size;
}



猜你喜欢

转载自blog.csdn.net/deng0zhaotai/article/details/70172793