user934902 user934902 - 1 year ago 130
Swift Question

Move collection view on button click (swift)

I have a collectionView that I am using to display my onboarding screen. Each cell takes the full width and height of the view and currently I have it working fine swiping between each cell (page).

I have to implement a next button. This button will just move the collectionView over 1 index on each click (till the end). I am just trying to make it move right now and even though there a few similar questions I have not been able to come up with a solution this far.

This is what I have tried

@IBAction func nextPageButtonClicked(_ sender: AnyObject) {
let visibleItems: NSArray = self.collectionView.indexPathsForVisibleItems as NSArray
let currentItem: NSIndexPath = visibleItems.object(at: 0) as! NSIndexPath
let nextItem: NSIndexPath = NSIndexPath(row: currentItem + 1, section: 0)
self.collectionView.scrollToItem(at: nextItem as IndexPath, at: .left, animated: true)

I get an error about performing the binary operator on line 4 (currentItem + 1) but even if I hard code the number and try and run it, I still dont get the scroll to function

Answer Source

You are trying to increment an indexPath, you must increment the indexPath's row.

let nextItem: NSIndexPath = NSIndexPath(row: currentItem.row + 1, section: 0)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download