Creative crypter
Creative crypter

Reputation: 1516

Swift 3 - CollectionView select not visible

every time i try to select a cell which is not visible, i get an exception:

let cell = collectionView.cellForItem(at: indexPath) as! CustomCell

Thats why i decided to first scroll to it so it gets visibile and then to select it:

collectionView.scrollToItem(at: indexPath, at: [], animated: true)
let cell = collectionView.cellForItem(at: indexPath) as! CustomCell

But i still get:

fatal error: unexpectedly found nil while unwrapping an Optional value

for this line:

let cell = collectionView.cellForItem(at: indexPath) as! CustomCell

Anybody could help me with this issue?

Thanks and Greetings!

Upvotes: 0

Views: 157

Answers (1)

Monika mitruka
Monika mitruka

Reputation: 96

We have did select method in UICollectionViewDelegate.

 func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
      //here you can access the cell 
      guard let cell = collectionView.cellForItem(at: indexPath) as? 
      CustomCell else { return }
      //write your code here
}

Upvotes: 3

Related Questions