Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 914
user934902 Avatar asked Nov 28 '22 02:11

user934902


2 Answers

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)

    }
}
like image 159
Amit gupta Avatar answered Dec 09 '22 14:12

Amit gupta


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)
}
like image 36
Callam Avatar answered Dec 09 '22 12:12

Callam