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
Try these methods for left as well as right increment of your collection cell
For right increment
@IBAction func Btn_RightAction(_ sender: Any)
{
let visibleItems: NSArray = self.collectionView.indexPathsForVisibleItems as NSArray
let currentItem: IndexPath = visibleItems.object(at: 0) as! IndexPath
let nextItem: IndexPath = IndexPath(item: currentItem.item + 1, section: 0)
if nextItem.row < ImgArr.count {
self.collectionView.scrollToItem(at: nextItem, at: .left, animated: true)
}
}
For left increment
@IBAction func Btn_LeftAction(_ sender: Any)
{
let visibleItems: NSArray = self.collectionView.indexPathsForVisibleItems as NSArray
let currentItem: IndexPath = visibleItems.object(at: 0) as! IndexPath
let nextItem: IndexPath = IndexPath(item: currentItem.item - 1, section: 0)
if nextItem.row < ImgArr.count && nextItem.row >= 0{
self.collectionView.scrollToItem(at: nextItem, at: .right, animated: true)
}
}
You are trying to increment an indexPath, you must increment the indexPath's row.
let nextItem = NSIndexPath(row: currentItem.row + 1, section: 0)
Example
@IBAction func nextPageButtonClicked(_ sender: AnyObject) {
guard let indexPath = collectionView.indexPathsForVisibleItems.first.flatMap({
IndexPath(item: $0.row + 1, section: $0.section)
}), collectionView.cellForItem(at: indexPath) != nil else {
return
}
collectionView.scrollToItem(at: indexPath, at: .left, animated: true)
}
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