[英]Recalculate the height of the UITableViewCell when the text of the label changes
因此,当其标签的文本更改时,我在更新UITableViewCell
的高度时遇到问题。
我不擅长解释事物,因此我在Github上创建了一个存储库,以便您可以抓住并运行。 当您在表格视图中上下滚动(以重新使用单元格)时,该问题应该会出现。
我所做的是 :
UILabel
。 RxSwift
在视图模型中注册更改,并相应地更新UITable
的文本。 UITableViewController
)重新计算其高度。 tableView.beginUpdates
和tableView.endUpdates
来更新单元格的高度。 结果 :
我试过了
tableView.reloadData()
。 ->无限循环 tableView.reloadRows()
->可以,但是我不知道为什么。 我要实现的目标:
一些代码片段:(尽管最好检查回购。):
单元寄存器视图模型
override func awakeFromNib() {
super.awakeFromNib()
viewModel.title
.observeOn(MainScheduler.instance)
.subscribe(onNext: { [weak self] title in
guard let cell = self else { return }
cell.label.text = title
cell.delegate?.requestSizeRecalculate(cell: cell)
})
.disposed(by: disposeBag)
}
委托UITableViewController中的方法
func requestSizeRecalculate(cell: SimpleCell) {
print("Size recalculating....")
method1(cell: cell)
//method2(cell: cell)
//method3(cell: cell)
}
private func method1(cell: SimpleCell) {
// Will not cause infinite loop but will have duplicates.
cell.setNeedsUpdateConstraints()
tableView.beginUpdates()
tableView.endUpdates()
}
private func method2(cell: SimpleCell) {
// Will cause infinite loop
tableView.reloadData()
}
private func method3(cell: SimpleCell) {
// This method works pretty well.
if let indexPath = tableView.indexPath(for: cell) {
tableView.reloadRows(at: [indexPath], with: .none)
}
}
这是我第一次在Stackoverflow上提问。 我知道我可能使事情变得复杂了。 但是,如果有人可以根据您的经验提供任何建议,我将不胜感激!
你可以做:
tableView.beginUpdates()
tableView.reloadRows(at: [indexPathOfCell], with: .none)
tableView.endUpdates()
我看过您的代码。 现在,您无需计算行高。 当您仅给出top,lead,bottom和Trailing约束时。 Xcode将计算标签的高度,并根据标签的高度增加单元格的大小。 您只需要通过一种方法。
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat
{
return UITableViewAutomaticDimension
}
您已正确完成所有操作。 您只需要编写上述方法。 现在不需要此方法。
extension ViewController: SimpleCellDelegate {
func requestSizeRecalculate(cell: SimpleCell) {
print("Size recalculating....")
我已通过更改在此链接上上传了您的项目。 在数组中添加了1个更大的文本来测试自我调整大小。
这是Out的屏幕截图:-
我希望这个答案对您有帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.