iOS 计算带有行间距的字符串的高度

这个是计算普通字符串的....NSString的!

- (CGSize)sizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size lineBreakMode:(NSLineBreakMode)lineBreakMode NS_DEPRECATED_IOS(2_0, 7_0, "Use -boundingRectWithSize:options:attributes:context:"); // NSTextAlignment is not needed to determine size





而带有行间距的字符串是NSAttributedString, 属性字符串,比NSString 多出了很多属性

- (CGRect)boundingRectWithSize:(CGSize)size options:(NSStringDrawingOptions)options attributes:(NSDictionary *)attributes context:(NSStringDrawingContext *)context NS_AVAILABLE_IOS(7_0);


这样 就不用计算别的其他东西了...


补充,自己闲着没事,就封装了一个方法...欢迎大家使用:


#pragma mark - 计算cell高度  str 字符串长度 typefaceName字体内容 typefaceSize字体大小 scopeWidth显示范围的宽  scopeHeight显示范围的高
- (NSInteger )HeightStr:(NSString *)str typefaceName:(NSString *)typefaceName typefaceSize:(NSInteger)typefaceSize scopeWidth:(NSInteger)scopeWidth scopeHeight:(NSInteger)scopeHeight
{
    
    NSDictionary * dic = [NSDictionary dictionary];
    
    //1.获得要显示的文本 str
    NSString * CellStr = str;
    
    //计算高度
    if (typefaceName == nil) {
        dic = @{NSFontAttributeName:[UIFont systemFontOfSize:typefaceSize]};
    }else{
        //字体类型 大小
        dic = @{NSFontAttributeName:[UIFont fontWithName:typefaceName size:typefaceSize]};
    }
    
    //字符串的显示范围
    CGSize scope = CGSizeMake(scopeWidth, scopeHeight);
    
    CGRect rect = [CellStr boundingRectWithSize:scope options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];

    int cellH = rect.size.height + 20;
    
    return cellH;
}

你可能感兴趣的:(IOS,UI)