[iOS]UILabel计算文本高度

[iOS]UILabel计算文本高度

// 计算字符串高度
+ (float)jisuanLabHighWithString:(NSString *)string Width:(float)width FontSize:(float)size {
    UIFont *font = [UIFont systemFontOfSize:size];
    // NS_AVAILABLE(10_11, 7_0)
    CGRect rect = [string boundingRectWithSize:CGSizeMake(width, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : font} context:nil];
    return rect.size.height;
}
/// 获取固定宽度的文本高度
+ (float)textHeightWithString:(NSString *)text FontSize:(float)fontSize Width:(float)viewWidth {
    UILabel *tempLab = [UILabel new];
    [tempLab setFrame:CGRectMake(0, 0, viewWidth, 1000)];
    [tempLab setText:text];
    [tempLab setFont:[UIFont systemFontOfSize:fontSize]];
    [tempLab setNumberOfLines:0];
    [tempLab sizeToFit];
    CGRect curRect = tempLab.frame;
    curRect.size.width = viewWidth;
    tempLab.frame = curRect;
    return curRect.size.height;
}
应用

评论列表,三行一下全部展示,超过三行需要展开才能查看全文。

- (void)initCellWithObject:(id)object IndexPath:(NSIndexPath *)indexPath {
    [self releaseAction];
    if (object) {
        _dataModel = (GAMessageModel *)object;
        NSInteger tempLine = [GAPublicClass textLineWithString:_desLab.text FontSize:13.0 Width:DE_SCREENWIDTH - 74];
        if (tempLine > 3) {
            _funBut.hidden = NO;
            if (!_dataModel.dIsShowAll) {
                // 不展示
                [_funBut setTitle:@"全部" forState:UIControlStateNormal];
                [_desLab setNumberOfLines:3];
            } else {
                // 展示
                [_funBut setTitle:@"收起" forState:UIControlStateNormal];
                [_desLab setNumberOfLines:0];
            }
        } else {
            [_desLab setNumberOfLines:0];
        }
    }
}
/// 获取固定宽度的文本有多少行
+ (NSInteger)textLineWithString:(NSString *)text FontSize:(float)fontSize Width:(float)viewWidth {
    UILabel *tempLab = [UILabel new];
    [tempLab setFrame:CGRectMake(0, 0, viewWidth, 1000)];
    [tempLab setText:text];
    [tempLab setFont:[UIFont systemFontOfSize:fontSize]];
    [tempLab setNumberOfLines:0];
    [tempLab sizeToFit];
    CGRect curRect = tempLab.frame;
    curRect.size.width = viewWidth;
    tempLab.frame = curRect;
    NSInteger lines = curRect.size.height / (fontSize+1);
    return lines;
}

示意图




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值