[英]UICollectionView Crash on reloadData
UICollectionview加載了簡單單元格,並且有一個簡單的int變量用於計算該部分中的項目數。
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return viewCount
}
當viewCount(最初為45)的值更改為較低的數字(例如12)時,應用程序崩潰。
這是更新項目計數的錯誤消息:
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'UICollectionView received layout attributes for a cell with an index path that does not exist: <NSIndexPath: 0x17402fbe0> {length = 2, path = 0 - 12}'
我嘗試重新加載數據並使緩存失效,並在此處說。 這沒有用。 我也嘗試在使緩存失效之前重新加載indexSet。 這也沒有幫助。
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if textField == countTextField {
viewCount = Int(textField.text!)!
textField.resignFirstResponder()
let indexSet = IndexSet(integer: 0)
// collectionView.reloadSections(indexSet)
collectionView.reloadData()
collectionView.collectionViewLayout.invalidateLayout()
}
return true
}
我使用2個自定義UICollectinViewLayout
,我也將shouldInvalidateLayout
設置為true。 有幫助嗎?
更新
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "DemoCell", for: indexPath) as! DemoCollectionViewCell
cell.indexLabel.text = "\(indexPath.item + 1)"
return cell
}
@IBAction func showLayout1(_ sender: Any) {
currentLayout = DemoACollectionViewLayout()
animateLayout()
}
@IBAction func showLayout2(_ sender: Any) {
currentLayout = DemoBCollectionViewLayout()
animateLayout()
}
func animateLayout() {
UIView.animate(withDuration: 0.3) { [weak self] value in
guard let `self` = self else { return }
self.collectionView.collectionViewLayout.invalidateLayout()
self.collectionView.collectionViewLayout = self.currentLayout!
}
}
這是示例項目。
更新 :我已更新使用dataObject重新加載UICollectionView
但是當我無效時,UICollectionViewLayout中的緩存未被清除。
當collectionView的項目數已更改時,必須清除緩存。
guard let views = collectionView?.numberOfItems(inSection: 0)
else {
cache.removeAll()
return
}
if views != cache.count {
cache.removeAll()
}
if cache.isEmpty {
//Layout attributes
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.