gpt4 book ai didi

ios - 在 HeightForRowAt 中获取行高

转载 作者:行者123 更新时间:2023-11-28 14:04:42 24 4
gpt4 key购买 nike

我有一个带有自定义 UITableViewCellUITableViewController。每个单元格有 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
}
}

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

最佳答案

基于 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 中的导出拖到 Storyboard 中的 View Controller 来连接数据源和委托(delegate)。之后,您仍然需要将其添加到 ViewController 的 swift 文件中的 ViewDidLoad 中。 enter image description here

tableView.delegate = self
tableView.dataSource = self

我还为 tableView 声明了一个 Outlet,如下所示,并连接到 Interface Builder Storyboard 中。

@IBOutlet weak var tableView: UITableView!

enter image description here

关于ios - 在 HeightForRowAt 中获取行高,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53107580/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com