zoukankan      html  css  js  c++  java
  • 计算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进行测试,可以发现显示正常。

  • 相关阅读:
    pom.xml配置文件内容记录
    如何做出一个博客网站
    PHP中cookie和session的区别
    PHP链接mysql 出现:由于目标计算机积极拒绝,无法连接
    DOM增删操作(创建删除表格)
    DOM增删操作(select动态增加和删除以及清空)
    DOM增删改操作
    DOM操作表格
    SSD性能测试
    我的配置单
  • 原文地址:https://www.cnblogs.com/xiaolingling1126/p/5230830.html
Copyright © 2011-2022 走看看