I have a UICollectionView
whose source data changes sometimes when offscreen. To update it when it returns, I wrote in the CollectionViewController
:
override func viewWillAppear(animated: Bool) {
self.collectionView!.reloadData()
}
...and that works, but I never need to update more than one or two cells in my UICollectionView
, so I thought it'd be better if I replaced the above version with:
override func viewWillAppear(animated: Bool) {
self.collectionView!.reloadItemsAtIndexPaths(myArrayOfIndexPaths)
}
...but when I do, Xcode gives me an error saying:
Operand of postfix '!' should have optional type, delete '!'".
When I delete the '!', it says that UICollectionView
doesn't have a member named reloadItemsAtIndexPaths
. What am I doing wrong?
From your code it looks like you have declared your collectionView as Optional (with ?) at the end and maybe linked it to your storyboard using an @IBOutlet. To fix your issue you should remove the ? from the :
@IBOutlet var collectionView: UICollectionView?
and substitute it with:
@IBOutlet var collectionView: UICollectionView!
this way you are telling the compiler that your collectionView definitely exists (because you have linked it from your storyboard).
Alternatively, you can bind your collectionView by doing this:
if let collectionView = collectionView {
collectionView.reloadItemsAtIndexPaths(myArrayOfIndexPaths)
}
Swift 4 reload all items in section
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
var indexPaths: [NSIndexPath] = []
for i in 0..<collectionView!.numberOfItems(inSection: 0) {
indexPaths.append(NSIndexPath(item: i, section: 0))
}
collectionView?.reloadItems(at: indexPaths as [IndexPath])
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With