tableview的那些事儿IOSiOS学习笔记

xib tableViewCell 自适应高度

2015-11-26  本文已影响687人  劉光軍_MVP

1 在xib中给各个控件添加约束


21D75143-9199-4C77-ABBF-9D474C1CB519.png

2 在model模型中 添加属性

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

3 在cell中重写model的set方法 在set方法中给cell中的控件赋值 注意 在计算label的宽度的时候 要手动计算 因为默认宽度是xib 中的宽度 320 , 然后 将cell中的各个控件的高度赋值给model中的cellHeight

- (void)setRecordModel:(AdjustAuditRecordModel *)recordModel {
_checkStatusLabel.text = [NSString stringWithFormat:@"操作状态:%@", _recordModel.audit_status];
    _noteLabel.text = [NSString stringWithFormat:@"备注/意见:%@", _recordModel.audit_opinion];
    CGFloat width = kScreenWidth-26;
    CGFloat noteHeight = [UILabel getLabelHeightByWidth:width Title:_noteLabel.text font:_noteLabel.font];
//    DLog(@"noteHeight %f   ", noteHeight);
    _recordModel.cellHeight = noteHeight +75;
}

4 最主要的是在我们控制器内部加上协议方法

- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 80.f;
}

注意这里的预估高度当然是越接近越好,但其实还是比较随意,即使和真实高度差大一点也没有关系。
5 在viewController中的tableviewDelegate方法中, 取出model中的cellHeight ,然后返回cellHeight
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    AdjustAuditRecordModel *model = _stepList[indexPath.row];
//    DLog(@"cell height%f",model.cellHeight);
    return model.cellHeight;
}

注意:只能在iOS 9.0以上能使用,在iOS7上 constant报错, iOS8 没有试验

上一篇 下一篇

猜你喜欢

热点阅读