我正在更改位于自定义 UITableViewCell 中的标签上的 numberOfLines
属性,当单元格被点击时。但是,直到第二次点击时,这才会反射(reflect)在 UI 中。该单元格在 TableView 中配置为原型(prototype)单元格,最初有 2 行。
有趣的是,当我在我的 tapped()
函数运行前后打印出 numberOfLines
值时,值开始不同,然后同步 - 在第一个之后点击,我在函数运行前看到 2 行,然后在函数运行后看到 0 行。然而,在随后的点击之后,我在我的函数前后看到了相同的值,这使得它看起来好像没有做任何事情,即使 UI 确实拉伸(stretch)和收缩单元格,并且 numberOfLines
值是在 didSelectRowAtIndexPath
函数运行时更改。
我只在 tableView.reloadRows()
中看到这种行为。如果我使用 tableView.reloadData()
进行完整更新,单元格会在第一次被点击时适本地增长和折叠。然而,这感觉有点笨拙,而且动画效果不如 reloadRows()
那样好。
TableView 实现
func tableView(_ tableView: UITableView,
didSelectRowAt indexPath: IndexPath) {
guard let cell = tableView.cellForRow(at: indexPath) as? ReviewTableViewCell
else { return }
let data = tableData[indexPath.row]
print("old number of lines: \(cell.detailLabel.numberOfLines)")
//data.isOpen is set to false initially
cell.tapped(data.isOpen)
tableData[indexPath.row].isOpen = !data.isOpen
tableView.reloadRows(at: [indexPath], with: .fade)
print("old number of lines: \(cell.detailLabel.numberOfLines)")
// tableView.reloadData()
}
自定义表格 View 单元格方法
func tapped(_ isOpen: Bool) {
if !isOpen {
detailLabel.numberOfLines = 0 }
else {
detailLabel.numberOfLines = 2 }
}
如果 numberOfLines
设置为 0,我希望此代码在使用 tableView.reloadRows()
重新加载单元格后展开单元格,并在单元格为 0 时折叠单元格设置为 2。这确实有效,但只有在点击单元格两次以上之后。这也适用于第一次点击。
这是显示问题的 gif 链接:https://imgur.com/a/qe2uAXj
这是一个示例项目,与我的应用程序中发生的事情类似:https://github.com/imattice/CellLabelExample
最佳答案
要明确一点,要让这个技巧起作用,UILabel
通常必须在它的父 View 的每一侧都受到约束,这样当它更改其 intrinsicContentSize
时就能够插入每一侧以容纳文本。
话虽如此,尝试用这两种方法包装 tapped 方法:
tableView.beginUpdates()
if !isOpen {
detailLabel.numberOfLines = 0
}
else {
detailLabel.numberOfLines = 2
}
tableView.endUpdates()
当然tableview必须设置为automatic size:
tableView.estimatedRowHeight = <#What you want#>
tableView.rowHeight = UITableView.automaticDimension
关于ios - 点击 TableViewCell 时 UILabel 未按预期更新的行数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55911738/