美文网首页
cell自定义高度

cell自定义高度

作者: ios_stand | 来源:发表于2016-08-26 16:12 被阅读0次
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath

{
    
    //取出模型
    
    XMGTopic *topic = self.topics[indexPath.row];
    
    CGFloat textY = 55;
    
    //根据文本宽度算出模型中text的高度
    
    CGFloat textH = [topic.text boundingRectWithSize:CGSizeMake(self.view.frame.size.width-40, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:14]} context:nil].size.height;
    
    return textH+textY+44+10+10;
    
}

//开发中,不建议在- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath方法中计算每行cell的高度(每次滑动后都要重新计算当前展示cell的高度),建议在模型.h中去增加一个属性:

/** cell的高度*/
@property (nonatomic, assign) CGFloat cellHeight;

.m实现cellHeight的get方法

- (CGFloat)cellHeight

{
    
    if (!_cellHeight) {
        
        CGFloat textY = 55;
        
        CGFloat textH = [self.text boundingRectWithSize:CGSizeMake([UIScreen mainScreen].bounds.size.width - 40, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:14]} context:nil].size.height;
        
        _cellHeight = textH+textY+44+10+10;
        
    }
    
    return _cellHeight;
    
}

//然后在tableview代理方法中实现:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath

{
    
    //取出模型
    
    XMGTopic *topic = self.topics[indexPath.row];
    
    return topic.cellHeight;
    
}

这样做的好处是把cell的高度存在模型中,不用每次都重新计算

相关文章

网友评论

      本文标题:cell自定义高度

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