簡體   English   中英

如何更新自調整表格視圖的高度?

[英]How to update self-sizing tableview's height?

如果將自定義視圖放在單元格中,如果自定義視圖的高度已更改,如何通知tableview更新單元格的高度? 我試過invalidateIntrinsicContentSize,但是不起作用。 ReloadData有效,但我懷疑是否使用

self.superview?.superview?.superview as! UITableView).reloadData()

是一個很好的實現。 我在這里看到了類似的問題但這全都是關於標准庫的視圖。 這個這個沒有答案。

您正在朝正確的方向思考。 但是,您的方法存在兩個問題:

  1. reloadData重新加載整個表視圖,並且不對更改進行動畫處理。
  2. 當Apple更改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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM