贡献作者 -【XJDomain】
博客XJ: https://my.oschina.net/shengbingli/blog
GitHub: https://github.com/lishengbing/XJQRCodeToolDemo
简单明了的定时器操作:
// MARK: - 定义属性
var cycyleTimer : Timer?
// MARK: - 对定时器的操作
extension XJRecommendCycleView {
// 添加定时器
fileprivate func addCycleTimer() {
cycyleTimer = Timer(timeInterval: 2.0, target: self, selector: #selector(self.scrollToNext), userInfo: nil, repeats: true)
RunLoop.main.add(cycyleTimer!, forMode:RunLoopMode.commonModes)
}
// 移除定时器
fileprivate func removeCycleTimer() {
// 从运行循环中移除
cycyleTimer?.invalidate()
cycyleTimer = nil
}
// 定时器的方法
@objc fileprivate func scrollToNext() {
// 1.获取滚动的偏移量
let cycleWidth = collectionView.bounds.width
let currentOffsetX = round(collectionView.contentOffset.x / cycleWidth) * cycleWidth
let offsetX = currentOffsetX + collectionView.bounds.width
// 2.滚动到该位置
collectionView.setContentOffset(CGPoint(x: offsetX, y: 0), animated: true)
}
}