I am trying to create horizontal slider like Flipkart. I am using collectionView with Horizontal scrolling and paging. Cell contains imageView. I am succeed in scrolling items h
Here is my slightly improved solution. It stops the scroll when user manually starts to scroll and restarts it if the cell is reused again.
var x = 0
weak var timer: Timer?
var cashbackOffers = [CashbackOffer]() {
didSet {
collectionView.reloadData()
autoScroll()
}
}
fileprivate func autoScroll() {
x = 0
timer?.invalidate()
timer = Timer.scheduledTimer(withTimeInterval: 3.0, repeats: true) { [weak self] timer in
guard let `self` = self else {
timer.invalidate()
return
}
if self.cashbackOffers.count == 0 {
return
}
if self.x < self.cashbackOffers.count {
let indexPath = IndexPath(item: self.x, section: 0)
self.collectionView.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: true)
self.x = self.x + 1
} else {
self.x = 1
self.collectionView.scrollToItem(at: IndexPath(item: 0, section: 0), at: .centeredHorizontally, animated: true)
}
}
timer?.fire()
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if scrollView.isTracking {
timer?.invalidate()
}
}
override func awakeFromNib() {
super.awakeFromNib()
autoScroll()
}