CollectionView move to next cell automatically swift

后端 未结 11 2203
耶瑟儿~
耶瑟儿~ 2021-01-31 21:05

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

11条回答
  •  醉酒成梦
    2021-01-31 21:28

    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()
    }
    

提交回复
热议问题