【问题标题】:Ensuring cell height adjusts per custom UITableViewCell?确保每个自定义 UITableViewCell 调整单元格高度?
【发布时间】:2016-03-05 23:45:54
【问题描述】:

我已经定义了一个自定义 UITableViewCell,在 UITableViewController 中使用,它显示在我的表格中。问题是单元格保留了原始高度,作为默认的 UITableViewCell,而不是使用我在“大小检查器”->“表格视图单元格”->“行高”中指定的高度。

我的自定义单元格加载如下:

tableView.registerNib(UINib(nibName: "CustomTableViewCell", bundle: nil), forCellReuseIdentifier: "Cell")

然后在tableView函数中:

let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! CustomTableViewCell
cell.titleLabel?.text = "title text"
cell.detailTextLabel?.text = "detail text to go here"

我曾尝试如下手动设置高度,但这也不起作用:

cell.frame.size.height = 100.0

对于将单元格置于正确高度的正确方法有什么想法吗?

XCode 7.2.1,iOS 9

【问题讨论】:

    标签: ios xcode uitableview swift2


    【解决方案1】:

    如果您的 tableview 单元格数据是静态的并且每个单元格的高度相同,请覆盖此函数(如果您使用 UITableViewController 子类)以返回您的单元格的高度。

    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        return 100.0
    }
    

    否则,如果您的数据是动态的,并且您希望每个单元格都有自己的高度,请在viewDidLoad 方法中设置:

       tableView.estimatedRowHeight = 44.0
       tableView.rowHeight = UITableViewAutomaticDimension 
    

    不要忘记对单元格中的所有视图(例如UILabelUIImageView 等)应用约束,以让tableView 自动计算和调整单元格高度。

    【讨论】:

      【解决方案2】:

      行高是表格的一个属性。在您的表格视图控制器的viewDidLoad 中,可能就在您已经说过的地方:

      tableView.registerNib(UINib(nibName: "CustomTableViewCell", bundle: nil), forCellReuseIdentifier: "Cell")
      

      也这样说:

      tableView.rowHeight = 100
      

      【讨论】:

        【解决方案3】:

        设置

        TableView.estimatedRowHeight 
        

        做有意义的事

        确保您的约束条件允许正确调整大小。这是最重要的部分。如果不能,还有其他几种方法。但你不想去那里。这是迄今为止最方便的方法

        不要使用 rowHeight 或相关的委托/数据源函数

        【讨论】:

          【解决方案4】:

          在 Obj C 中,您可以在 UITableViewController 子类中实现此功能:

          - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
              return 100; // or whatever your cell height is
          }
          

          也许在 Swift 中有一个等价物

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2012-11-11
            • 2020-10-15
            • 2018-06-28
            • 1970-01-01
            • 1970-01-01
            • 2023-01-16
            相关资源
            最近更新 更多