美文网首页iOS开发知识
手把手教你怎么如何使用[label sizeToFit]实现最简

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

作者: 太阳骑士索拉尔 | 来源:发表于2019-03-05 21:30 被阅读1次

    前言

    • 文章很简单,就是通过给定UILabel的宽度,通过[label sizeToFit]来计算出UIlabel的高度
    • 将算出来的高度依次存入数组中,从而实现高度的缓存,避免卡顿
    • 非常简单,缺点就是不太精准,因为有多次的数据转换

    参考文章

    代码实现

    //写在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];
    }
    
    

    相关文章

      网友评论

        本文标题:手把手教你怎么如何使用[label sizeToFit]实现最简

        本文链接:https://www.haomeiwen.com/subject/dmsauqtx.html