[英]How to update self-sizing tableview's height?
您正在朝正確的方向思考。 但是,您的方法存在兩個問題:
reloadData
重新加載整個表視圖,並且不對更改進行動畫處理。 UITableView
視圖層次結構時,向上移動超級視圖鏈肯定會中斷。 他們之前已經做過,所以他們可能會再做一次。 要解決第一個問題,您應該調用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?()
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.