Reputation: 532
Hi i have been struggle with this probleme for some time and cant figure it out.
What i would like to do is, press a button inside a collectionview cell, and perform a transition to next cell.
This is the function i want to call that is inside the the collectionview controller class:
func done(){
let scrollIndex: NSIndexPath = NSIndexPath(item: 1, section: 0)// NSIndexPath(forItem: 0, inSection: 0)
CollectionViewet.scrollToItem(at: scrollIndex as IndexPath, at: .centeredHorizontally, animated: true)
}
What happens is that when i call a function from collectionview controller, it give me this
Unexpectedly found nil while unwrapping an Optional value
What i am doing wrong?
Upvotes: 1
Views: 650
Reputation: 5259
The UICollectionViewController
has a subview by default called collectionView
which you should use to scroll to an item
So if you override the data source delegate methods properly you should be able to scroll as follows
func done() {
let numberOfRows = collectionView?.numberOfItems(inSection: 0) ?? 0
guard numberOfRows > 1 else { return }
let indexPath = IndexPath(row: 1, section: 0)
collectionView?.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: true)
}
I added the guard
line to prevent the app from crashing in case of an empty data for some reason.
Upvotes: 1