UICollectionView - Horizontal AutoScroll with Timer

最后都变了- 提交于 2019-12-03 21:53:14
H.Jacob

In the custom class of your collectionViewCell:

self.contentView.frame = self.bounds;
self.contentView.autoresizingMask = UIViewAutoresizingFlexibleWidth |
                                    UIViewAutoresizingFlexibleHeight;

and remove any other width calculations.

I am using like this

declare variable

var timer:Timer!

call from viewDidLoad

self.addTimer()


func addTimer() {
    let timer1 = Timer.scheduledTimer(timeInterval: 3.0, target: self, selector: #selector(self.nextPage), userInfo: nil, repeats: true)
    RunLoop.main.add(timer1, forMode: RunLoopMode.commonModes)
    self.timer = timer1
}


func resetIndexPath() -> IndexPath {
    let currentIndexPath = self.collectionView.indexPathsForVisibleItems.last
    let currentIndexPathReset = IndexPath(item: (currentIndexPath?.item)!, section: 0)
    self.collectionView.scrollToItem(at: currentIndexPathReset, at: UICollectionViewScrollPosition.left, animated: true)
    return currentIndexPath!
}

func removeTimer() {
    if self.timer != nil {
        self.timer.invalidate()
    }
    self.timer = nil
}


func nextPage() {
    let currentIndexPathReset:IndexPath = self.resetIndexPath()
    var nextItem = currentIndexPathReset.item + 1
    let nextSection = currentIndexPathReset.section
    if nextItem == productImage.count{
        nextItem = 0
    }
    var nextIndexPath = IndexPath(item: nextItem, section: nextSection)
    if nextItem == 0 {
        self.collectionView.scrollToItem(at: nextIndexPath, at: UICollectionViewScrollPosition.left, animated: false)
    }
    self.collectionView.scrollToItem(at: nextIndexPath, at: UICollectionViewScrollPosition.left, animated: true)
}



func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
    self.addTimer()

}

func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
    self.removeTimer()
}

func scrollViewDidScroll(_ scrollView: UIScrollView) {
    var visibleRect = CGRect()
    visibleRect.origin = collectionView.contentOffset
    visibleRect.size = collectionView.bounds.size
    let visiblePoint = CGPoint(x: visibleRect.midX, y: visibleRect.midY)
    let visibleIndexPath: IndexPath? = collectionView.indexPathForItem(at: visiblePoint)
    pageControlView.currentPage = (visibleIndexPath?.row)!
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!