首页 > 解决方案 > 获取 HeightForRowAt 中的行高

问题描述

我有UITableViewController一个自定义的UITableViewCell. 每个单元格有 2 个标签。选择单元格后,它会扩展为固定值,我通过tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat. 我还设置了 rowHeight = UITableViewAutomaticDimension ,因为某些单元格必须显示多行文本。我想要实现的是当需要扩展单元格时,我想在其当前高度上增加 50 个点。所以这里的问题是,我怎样才能得到单元格的当前高度,当rowHeight = UITableViewAutomaticDimension设置时?

这是选定状态的固定高度的代码:

override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if selectedIndexPath == indexPath {
            return selectedHeight
        }else{

        return tableView.estimatedRowHeight
        }
    }

编辑:之后我还需要通过添加一些变量来更改它。

标签: iosswiftuitableview

解决方案


基于 HamzaLH 的回答,您可能会做这样的事情......

导入 UIKit

类 TableViewController: UITableViewController {

var selectedRow: Int = 999 {
    didSet {
        tableView.beginUpdates()
        tableView.endUpdates()
    }
}


override func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 5
}



override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    if indexPath.row == selectedRow {  //assign the selected row when touched
        let thisCell = tableView.cellForRow(at: indexPath)

        if let thisHeight = thisCell?.bounds.height {

            return thisHeight + 50

        }
    }
    return 60 //return a default value in case the cell height is not available
}

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    selectedRow = indexPath.row
}


override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

     let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath)


    cell.detailTextLabel?.text = "test"


    return cell
}

}

当 selectedRow 被更改时,我正在使用 didSet 对高度的扩展进行动画处理。

另外,不要忘记您可能仍然需要通过将 Interface Builder 中的插座拖到情节提要中的 View Controller 来连接您的数据源和委托。之后,您仍然需要将其添加到 ViewController 的 swift 文件中的 ViewDidLoad 中。 在此处输入图像描述

tableView.delegate = self
tableView.dataSource = self

我还为 tableView 声明了一个 Outlet,如下所示,并在 Interface Builder 故事板中连接。

@IBOutlet weak var tableView: UITableView!

在此处输入图像描述


推荐阅读