簡體   English   中英

為什么之前調用 reloadRows 時 UITableView setContentOffset 無法正常工作?

[英]Why does UITableView setContentOffset not work properly when reloadRows was called before?

之前調用tableView.reloadRows(at: , with: )時, tableView.setContentOffset(, animated: )似乎無法正常工作。

如果reloadRows被調用setContentOffset將 TableView 上下移動幾個像素,但不會滾動到正確的位置。 只有在第二次調用setContentOffset時,滾動才能正確執行。

這是一個已知問題,一個錯誤還是我做錯了什么?


代碼

這個問題可以用一個簡單的UIViewController重現,它只包含一個UINavigationBar和兩個UIBarButtonItems和一個UITableView

BarButtons 用於觸發reloadRowssetContentOffset TableView 包含 10 個標准UITableViewCell的簡單列表和一些文本。

class MyViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    @IBOutlet var tableView: UITableView!


    //  Actions
    @IBAction func leftBarButtonAction(_ sender: Any) {
        // Scroll up 100px
        tableView.setContentOffset(CGPoint(x: 0, y: self.tableView.contentOffset.y + 100), animated: true)
    }

    @IBAction func rightBarButtonAction(_ sender: Any) {
        // Reload first row
        tableView.reloadRows(at: [IndexPath(row: 0, section: 0)], with: .none)
    }


    //  TableView
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 10
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "defaultCell") ?? UITableViewCell()
        cell.textLabel?.text = "Item No \(indexPath.row)"
        return cell
    }

}
  • 顯示視圖控制器
  • 點擊 leftBarButton 觸發setContentOffset並向上滾動 TableView。 這工作正常
  • 點擊 rightBarButton 觸發reloadRows 第一行將被重新加載(不可見)
  • 點擊 leftBarButton 再次觸發setContentOffset TableView 只會輕微移動而不是正確滾動
  • 點擊 leftBarButton 再次觸發setContentOffset 現在滾動將再次起作用。

任何想法如何防止這種奇怪的行為?

    @IBAction func leftBarButtonAction(_ sender: Any) {
        // Scroll up 100px
       tableView.beginUpdates()
       tableView.setContentOffset(CGPoint(x: 0, y: self.tableView.contentOffset.y + 100), animated: true)
       tableView.endUpdates()
    }

只需用下面的代碼替換 leftBarButtonAction 的代碼。 希望它有效。 :)

tableView.reloadData()
tableView.layoutIfNeeded()
tableView.setContentOffset(CGPoint(x: 0, y: self.tableView.contentOffset.y + 100), animated: true)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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