The UICollectionview is loaded with simple cells, and there is a simple int variable to calculate the number of elements in the section.
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return viewCount
}
When the value of viewCount (initially 45) changes to a smaller number (say 12), the application crashes.
This is an error message to update the number of items:
*** 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}'
I tried reloading the data and canceled the caching, and also said here . It did not help. I also tried reloading indexSet before invalidating the cache. It didn’t help either.
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if textField == countTextField {
viewCount = Int(textField.text!)!
textField.resignFirstResponder()
let indexSet = IndexSet(integer: 0)
collectionView.reloadData()
collectionView.collectionViewLayout.invalidateLayout()
}
return true
}
I use 2 custom ones UICollectinViewLayout, and also set shouldInvalidateLayoutto true. Any help?
Update
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!
}
}
Here is the project.
: dataObject, UICollectionView, UICollectionViewLayout , .