iOS开发知识

手把手教你怎么如何使用[label sizeToFit]实现最简

2019-03-05  本文已影响1人  太阳骑士索拉尔

前言

参考文章

代码实现

//写在UILabel的扩展类里
+ (CGFloat)getHeightByWidth:(CGFloat)width title:(NSString *)title font:(UIFont *)font {
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, width, 0)];
    label.text = title;
    label.font = font;
    label.numberOfLines = 0;
    [label sizeToFit];
    CGFloat height = label.frame.size.height;
    return height;
}
//自定义cell里
+ (CGFloat)cellComment:(NSString *)comment size:(CGSize)contextSize {
    CGFloat commentHeigth = [UILabel getHeightByWidth:contextSize.width - 80 title:comment font:[UIFont systemFontOfSize:15.0]];
    return commentHeigth + 110;
}
//缓存高度(切忌写在heightOfrow里)
 CGFloat height = [ZDICommitPageTableViewCell cellComment:[_shortCommitPageModel.comments[i] contentCommitStr] size:CGSizeMake(self.view.frame.size.width, 0)];
            NSNumber *commentHeight = [NSNumber numberWithFloat:height];
            [_cellShortCommitHeightArray addObject:commentHeight];
//最好是网络请求到后直接返回主队列就调用
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return [_cellLongCommitHeightArray[indexPath.row] floatValue];
}

上一篇下一篇

猜你喜欢

热点阅读