[英]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 用於觸發reloadRows
和setContentOffset
。 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
}
}
setContentOffset
並向上滾動 TableView。 這工作正常reloadRows
。 第一行將被重新加載(不可見)setContentOffset
。 TableView 只會輕微移動而不是正確滾動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.