iOS DevelopmentiOS学习牛叉的demo

AutoLayout自适应Cell高度

2017-06-21  本文已影响33人  逆风g

iOS中tableview是一个经常用的控件,尤其它的cell高度计算令人头疼。考虑到tableview的性能优化,我们一般都会在model封装时提前计算好cell的高度,代理返回cell高度时,拿到model,直接给它已计算好的高度。iOS8.0之后,可以使用AutoLayout结合tableview的属性让cell自己计算出高度。

使用步骤

//给tableview设置一个默认高度
self.tableView.estimatedRowHeight = 45;
//告诉tableview,cell是自适应的
self.tableView.rowHeight = UITableViewAutomaticDimension;

常遇问题

不需这样

//    [self.tableView registerClass:NSClassFromString(@"MyTableViewCell1") forCellReuseIdentifier:cellId1];
//    [self.tableView registerClass:NSClassFromString(@"MyTableViewCell2") forCellReuseIdentifier:cellId2];

直接这样即可

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row<self.data1.count) {
        MyTableViewCell1 *cell = [tableView dequeueReusableCellWithIdentifier:cellId1 forIndexPath:indexPath];
        cell.model=self.data1[indexPath.row];
        return cell;
    }else
    {
        MyTableViewCell2 *cell = [tableView dequeueReusableCellWithIdentifier:cellId2 forIndexPath:indexPath];
        cell.model=self.data2[indexPath.row-self.data1.count];
        return cell;
    }
}
-(void)layoutSubviews
{
    [super layoutSubviews];
    self.lbl.text=self.model.contentStr;
}

要么:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row<self.data1.count) {
        MyTableViewCell1 *cell = [tableView dequeueReusableCellWithIdentifier:cellId1 forIndexPath:indexPath];
        MyModel1 *model=self.data1[indexPath.row];
        cell.lbl1.text=model.str1;
        cell.lbl2.text=model.str2;
//        cell.model=self.data1[indexPath.row];
        return cell;
    }else
    {
        MyTableViewCell2 *cell = [tableView dequeueReusableCellWithIdentifier:cellId2 forIndexPath:indexPath];
        MyModel2 *model=self.data2[indexPath.row];
        cell.lbl.text=model.contentStr;
//        cell.model=self.data2[indexPath.row-self.data1.count];
        return cell;
    }
}

很多情况下我们还是希望赋值操作是在cell类中完成时,也可以这样:

- (void)showData
{
    self.lbl1.text=self.model.str1;
    self.lbl2.text=self.model.str2;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row<self.data1.count) {
        MyTableViewCell1 *cell = [tableView dequeueReusableCellWithIdentifier:cellId1 forIndexPath:indexPath];
        cell.model=self.data1[indexPath.row];
        [cell showData];
        return cell;
    }else
    {
        MyTableViewCell2 *cell = [tableView dequeueReusableCellWithIdentifier:cellId2 forIndexPath:indexPath];
        cell.model=self.data2[indexPath.row-self.data1.count];
        [cell showData];
        return cell;
    }
}

进阶

假若label在contentview的多级子视图中也是可以实现cell高度自适应的。


image.png

原理也是同样的

demo效果

image.png image.png

demo在这里

上一篇 下一篇

猜你喜欢

热点阅读