计算tableview的高度

1、自定义一个Cell,拖一个label。设置cell的上下边与Cell.contentView间距0,其他约束随意。这样,lable对Cell的高度有了一个强约束。设置label的行数为0,高度不设。

2、感谢网友提醒,这里如果是iOS7,还是需要设置Cell的高度,不过可以非常简化,具体做法如下:

a、在ViewController中创建一个Cell的属性或成员变量,专门用于计算Cell高度。(做这一步是为了性能优化)比如self.tempCell

b、改写计算高度的回调

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

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

{

    id entity = self.dataSourceArray[indexPath.row];

    if (self.tempCell == nil) {

        self.tempCell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    }

    self.tempCell.bounds = CGRectMake(0,

                                      0,

                                      CGRectGetWidth(self.tableView.bounds),

                                      CGRectGetHeight(self.tempCell.bounds)

                                      );

    [self.tempCell resetCellWithEntity:entity];

         

    CGFloat height = [self.tempCell systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;

    return height > 44 ? height : 44;

}

self.tempCell.bounds = xxxxxx

写这行是因为tempCell创建出来后,默认宽度不一定符合实际情况。

c、在tempCell的resetCellWithEntity:方法中,加入类似这样的代码:

?

1

self.testLable.preferredMaxLayoutWidth = self.frame.size.width;

这是因为UILable根据preferredMaxLayoutWidth的值计算高度。默认不设置,表示由系统自动计算。但自动计算仅在iOS8以后有效。iOS7的话,还是需要手动设置的。

 

3、设置一个数据源,一个NSString的数组,放入长短不同的String进行测试,可以发现显示正常。

posted @ 2016-03-01 14:20  xiaolingling  阅读(2401)  评论(0编辑  收藏  举报