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

5 篇文章 0 订阅

这个是计算普通字符串的....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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值