ios - 获取 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
}
}
编辑:之后我还需要通过添加一些变量来更改它。
解决方案
基于 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!
推荐阅读
- node.js - 你如何使用 express 服务 css 文件?
- javascript - 如何在编译时从缓存参数中延迟“新功能”,等到它被使用
- sql - SQL中的增量下个月日期
- java - 如何操作http GET请求整数参数?
- firebase-analytics - 如何创建过去活跃但上周不活跃的用户群
- spring - 对 stockitem 进行 GET 调用的未经授权的 401 错误
- javascript - Paypal Checkout 按钮 - 环境配置 - Angular 6
- python - 删除列中的重复值
- docker - docker exec -ti 和 docker exec -it 有什么区别?
- python-2.7 - Python 2.7 - 立即将输出重定向到日志文件