在HeightForRowAt中获取行高

时间:2018-11-01 18:52:29

标签: ios swift uitableview

我有一个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
        }
    }

编辑:在此之后,我还需要通过向其中添加一些变量来对其进行更改。

2 个答案:

答案 0 :(得分:1)

基于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中。 enter image description here

tableView.delegate = self
tableView.dataSource = self

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

@IBOutlet weak var tableView: UITableView!

enter image description here

答案 1 :(得分:0)

您需要使用cellForRow获取单元格,然后获取单元格的高度。

let cell = tableView.cellForRow(at: indexPath)
let height = cell.bounds.height
相关问题