繁体   English   中英

Swift / XCode 6.4:如何以编程方式更改表视图控制器中单元格的高度

[英]Swift/XCode 6.4: how to programmatically change the height of cells in table view controller

在我的iOS应用中,有一个静态单元格的表格视图控制器,其中包含三种不同类型的单元格,其样式为“字幕”。 其中一个应该比其他两个要高得多,因为它应该包含很长的文本。 因此,在其大小检查器中,我将高度设置为100,但是当我通过其标识符在代码中创建一个新单元格时,该高度始终是默认高度。

我该如何更改? 我读过我应该重写此方法:

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

        return 100 //Whatever fits your need for that cell
}

但是我不知道如何使用它。 你能解释一下吗? 在此处输入图片说明

正如您说的那样, tableview单元格是静态的,因此您知道哪个单元格具有更高的高度,在heightForRowAtIndexPath中传递该单元格的indexpath ,并从那里返回该单元格的期望高度。 假设您的第一个单元格具有更高的高度,然后使用heightForRowAtIndexPath这样

 func tableView(tableView: UITableView,
    heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        if indexPath.row == 1 {
            return 100 //Whatever fits your need for that cell
        } else {
            return 50 // other cell height
        }
}

无需创建三个不同的原型单元,只需在单元上创建就足够了。

您可以按照帖子中提到的那样实现heightForRowAtIndexPath ,并使用cellForRowAtIndexPath获取单元格。 然后根据reuseIdentifier设置高度

override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
  if let cell = tableView.cellForRowAtIndexPath(indexPath) {
    if cell.reuseIdentifier == "SpecialCell" {
      return 100.0
    }
  }
  return 44.0
}

为什么不在Interface builder中使用2个不同的TableViewCells并选择要在cellForRowAtIndexPath中使用的合适的TableViewCells?

这是最简单的方法,您甚至可以在必要时在两种类型之间进行更多区分。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM