Reputation: 420
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.
Upvotes: 7
Views: 6261
Reputation: 2916
If you wants to scroll only on right side, then you can do something like this:
1) add the first object to the last
["apple","pen","book","bottle","apple"]
2) Now, as you have implemented the collectionView related delegate, dataSource methods so, there are no changes in that.
3) Now as this is scrolling automatically, when the last index reaches, you should scroll to first index without animation.
@objc func scrollAutomatically(_ timer1: Timer) {
if let coll = CV_Slider {
for cell in coll.visibleCells {
let indexPath: IndexPath? = coll.indexPath(for: cell)
//0,1,2,3,4
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)
if indexPath1.row == self.arr_img_Slide.count - 1 {
let indexPath2: IndexPath?
indexPath2 = IndexPath.init(row: 0, section: (indexPath?.section)!)
coll.scrollToItem(at: indexPath2!, at: .centeredHorizontally, animated: false)
}
}
}
}
}
Try and share your results.
Upvotes: 1
Reputation: 105
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
Upvotes: 2