Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to auto scroll UICollectionview in one direction swift?

good noon

I need to scroll uicollection view cell in one direction.

For Example:-

I have array with 4 data value -> ["apple","pen","book","bottle"].

I need to scroll Uicollectionview cell like this:

apple -> pen -> book -> bottle -> apple -> pen -> book -> bottle -> continue..

i used this code for auto scroll but in my case collection view scroll like:

apple -> pen -> book -> bottle <- (scroll back to first index) apple -> pen -> book -> bottle

code:

@objc func scrollAutomatically(_ timer1: Timer) {

      if let coll  = CV_Slider {
            for cell in coll.visibleCells {
                let indexPath: IndexPath? = coll.indexPath(for: cell)
                if ((indexPath?.row)!  < self.arr_img_Slide.count - 1){
                    let indexPath1: IndexPath?
                    indexPath1 = IndexPath.init(row: (indexPath?.row)! + 1, section: (indexPath?.section)!)

                    coll.scrollToItem(at: indexPath1!, at: .centeredHorizontally, animated: true)
                }
                else{
                    let indexPath1: IndexPath?
                    indexPath1 = IndexPath.init(row: 0, section: (indexPath?.section)!)
                    coll.scrollToItem(at: indexPath1!, at: .centeredHorizontally, animated: true)
                }

            }
        }
    }

Thanks in advance.

like image 627
Dhaval Umraliya Avatar asked Sep 11 '18 06:09

Dhaval Umraliya


1 Answers

1) return some very large number from ‘collectionView:numberOfItemsInSection:’ , like NSIntegerMax

2) in ‘collectionView:cellForItemAtIndexPath’ rather than just indexing directly into the datasource array to get the data to populate the cell use a % operator. I.E. do:

let item = datasource[indexPath.row % dataSource.count]

Instead of:

let item = datasource[indexPath.row]

This will give you an infinite and circular collectionView

like image 122
habs93 Avatar answered Nov 18 '22 07:11

habs93