如果我在单元格中放置自定义 View ,如果我的自定义 View 的高度发生变化,我如何通知表格 View 更新单元格的高度?我试过 invalidateIntrinsicContentSize 但这不起作用。 ReloadData 有效,但我怀疑是否使用
self.superview?.superview?.superview as! UITableView).reloadData()
最佳答案
您的思考方向是正确的。但是,您的方法存在两个问题:
reloadData
重新载入整个 TableView ,并且不会为更改设置动画。- 当 Apple 更改
UITableView
View 层次结构时,向上移动 super View 链必然会中断。他们以前做过,所以他们可能会再做一次。
要解决第一个问题,您应该改为调用 reloadRowsAtIndexPaths:withRowAnimation:
。这只会重新加载您在 indexPath 数组中指定的单元格。因此,您向它传递了一个仅包含您的单元格的 indexPath 的数组。
第二个问题有点棘手,因为 UITableViewCell
没有对其 UITableView
的引用(它不应该)。所以它不能直接告诉 UITableView
重新加载单元格。
你可以给每个单元格一个闭包,当它的高度改变时它应该执行。因此,您只需在自定义单元格中添加一个闭包属性:
class YourCustomTableViewCell: UITableViewCell {
var resizeClosure: (() -> Void)?
...
当您将单元格出队时,您在 UITableViewControllerDataSource
中设置了这个闭包:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell:UITableViewCell = tableView.dequeueReusableCellWithIdentifier("YourCustomCellIdentifier", forIndexPath: indexPath)
if let customCell = cell as? YourCustomTableViewCell {
customCell.resizeClosure = { [weak cell, weak tableView] in
if let currentIndexPath = tableView?.indexPathForCell(cell!) {
tableView?.reloadRowsAtIndexPaths([currentIndexPath], withRowAnimation: .Automatic)
}
}
}
return cell
}
只需确保将 tableView
添加到闭包的捕获列表中即可避免强引用循环。这是通过将 [weak tableView]
添加到闭包来完成的。
然后当单元格改变它的高度时,你只需执行闭包,单元格就会被重新加载:
func someFunctionThatChangesTheHeight() {
// change the height
resizeClosure?()
}
关于ios - 如何更新自动调整表格 View 高度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32799553/