关于cell自动布局约束实现高度自适应问题

之前写tableview列表高度动态显示时都是先计算内容高度,然后在tableview的cell高度代理方法里写每个cell高度

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

这样写比较麻烦,百度了几篇文章发现可以不用计算通过自动布局约束来实现高度的自定义,具体如下:

1.先在cell的类里给cell加约束,如果是xib直接加,纯代码可以用Masonry加相应约束,如下

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {

    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {

        _contentLab = [UILabel new];
        _contentLab.font = [UIFont systemFontOfSize:12];
        _contentLab.textColor = [UIColor blackColor];
        _contentLab.numberOfLines = 0;
        [self.contentView addSubview:_contentLab];

        [_contentLab mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.top.equalTo(self.contentView).offset(20);
            make.right.bottom.equalTo(self.contentView).offset(-20);
        }];

    }
    return self;

}

-(void)setModel:(MessageModel *)model{
    if (_model != model) {
        _model = model;
    }
    _contentLab.text = _model.content;
    
}

2.在ViewController里不用写cell高度代理方法,直接写如下代码即可实现高度自适应

self.tableView.estimatedRowHeight = 40;
self.tableView.rowHeight = UITableViewAutomaticDimension;

猜你喜欢

转载自www.cnblogs.com/zk1947/p/9139987.html