[英]CellForRowAtIndexPath gets called unexpectedly
我有一個超過12種不同類型的單元格的tableview。 我正在使用自動調整大小,並且所有單元格的約束均已正確設置。 一切都可以在iPhone模擬器上完美運行,但是當涉及到iPad模擬器時,一切都很好,直到
一旦我返回/重新打開該應用程序,表格視圖就會自動滾動到一個隨機位置,而且,一旦應用程序進入后台,cellForRowAtIndexPath就會被多次調用(僅針對周圍/包括顯示單元格的索引) ),看起來表格視圖會在應用程序進入后台后立即自動滾動。
我100%肯定在任何地方都沒有調用tableview.reloadData(),也沒有實現applicationDidEnterBackground。
想知道是否有人遇到過同樣的問題,潛在的原因是什么? 我使用XCode 9.3和iPad模擬器以及iOS 9.3和11.3進行了測試。
該場景如下所示,
我弄清楚了為什么,這是由於估計的高度不正確,並且tableview做一些奇怪的事情。 按下新的視圖控制器時,IOS 8 UITableView自調整大小單元格在視覺上跳躍/移動
我通過緩存單元格的高度來解決它,如果未緩存高度,則在UITableViewAutomaticDimension
中返回UITableViewAutomaticDimension
,如果緩存了高度,則返回UITableViewAutomaticDimension
。
偽代碼-Swift 4:
var cellEstimatedHeightCache = [Int: CGFloat]()
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
guard let height = cellEstimatedHeightCache[indexPath.row] else {
return UITableViewAutomaticDimension
}
return height
}
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
cacheCellHeight(row: indexPath.row, height: cell.frame.size.height)
}
private func cacheCellHeight(row: Int, height: CGFloat) {
cellEstimatedHeightCache[row] = height
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.