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}'
我尝试重新加载数据并使缓存无效以及所说的 here .这没有帮助。我还尝试在使缓存失效之前重新加载 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!
}
}
这是 sample项目。
更新:
我已经更新为使用 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
}
关于ios - 重新加载数据时 UICollectionView 崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45528286/