Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

collectionView: reloadData works, reloadItemsAtIndexPaths does not

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?

like image 364
Le Toucan Sale Avatar asked Jan 13 '15 20:01

Le Toucan Sale


2 Answers

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)
}
like image 113
Valentin Avatar answered Sep 30 '22 18:09

Valentin


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])
}
like image 36
Vac Avatar answered Sep 30 '22 19:09

Vac