CollectionView move to next cell automatically swift

后端 未结 11 2197
耶瑟儿~
耶瑟儿~ 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:29

    try this

    var index = 0
    var inForwardDirection = true
    var timer: Timer?
    
    @objc func scrollToNextCell() {
    
        //scroll to next cell
        let items = collectionViewTable.numberOfItems(inSection: 0)
        if (items - 1) == index {
            collectionViewTable.scrollToItem(at: IndexPath(row: index, section: 0), at: UICollectionViewScrollPosition.right, animated: true)
        } else if index == 0 {
            collectionViewTable.scrollToItem(at: IndexPath(row: index, section: 0), at: UICollectionViewScrollPosition.left, animated: true)
        } else {
            collectionViewTable.scrollToItem(at: IndexPath(row: index, section: 0), at: UICollectionViewScrollPosition.centeredHorizontally, animated: true)
        }
    
        if inForwardDirection {
            if index == (items - 1) {
                index -= 1
                inForwardDirection = false
            } else {
                index += 1
            }
        } else {
            if index == 0 {
                index += 1
                inForwardDirection = true
            } else {
                index -= 1
            }
        }
    
    }
    
    /**
     call this method when collection view loaded
     */
    func startTimer() {
        if timer == nil {
            timer = Timer.scheduledTimer(timeInterval: 5.0, target: self, selector: #selector(scrollToNextCell), userInfo: nil, repeats: true);
        }
    }
    

提交回复
热议问题