1.实现左右无限滚动
设置图片滚动的个数从原来的固定6个改为10000,一般用户会划完一万次
//MARK:遵循collectionView的数据源协议
extension RecommenCycleView: UICollectionViewDataSource{
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return (cycleModels?.count ?? 0) * 10000
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kCycleCellID, for: indexPath) as! CollectionCycleCell
cell.cycleModel = cycleModels![indexPath.item % cycleModels!.count]
return cell
}
}
![](https://img.haomeiwen.com/i3245733/04cb673f048d2c43.png)
//MARK: 遵循collection 代理协议
extension RecommenCycleView : UICollectionViewDelegate{
func scrollViewDidScroll(_ scrollView: UIScrollView) {
//1.滚动的偏移量,加上 0.5 让滚动到一半后自动加载到另一半。即默认帮他先多加载50%
let offsetX = scrollView.contentOffset.x + scrollView.bounds.width * 0.5
//2.计算pageController的currentIndex
pageControl.currentPage = Int(offsetX / scrollView.bounds.width) % (cycleModels?.count ?? 1)
}
}
![](https://img.haomeiwen.com/i3245733/a86a6824294a3af7.png)
这样设置后,可以一直右边滚动了
设置向左滚动:做法是设置滚动的开始页面为数据。
//定义模型属性
var cycleModels : [CycleModel]?{
//监听属性控件值的改变
didSet{
//1.刷新collectionView数据
collectionView.reloadData()
//2.设置pageControl的个数
pageControl.numberOfPages = cycleModels?.count ?? 0
//3.默认滚动到中间一个位置
let indexPath = NSIndexPath(item: (cycleModels?.count ?? 0), section: 0)
collectionView.scrollToItem(at: indexPath as IndexPath, at: .left, animated: false)
}
}
![](https://img.haomeiwen.com/i3245733/48e48758ec1f9365.png)
![](https://img.haomeiwen.com/i3245733/2b9b09b5f3d99a47.png)
2.定时器进行定时滚动
定义一个timer
//定义一个定时器,可选类型
var cycleTimer : Timer?
![](https://img.haomeiwen.com/i3245733/cd77d13dcfb54d80.png)
编写定时器的方法:
//MARK: 定义式的操作方法
extension RecommenCycleView{
//添加定时器
fileprivate func addCycleTimer(){
// 设置定时器的基本配置
cycleTimer = Timer(timeInterval: 3.0, target: self, selector: #selector(self.scrollToNext) , userInfo: nil, repeats: true)
//加入到主线程中
RunLoop.main.add(cycleTimer!, forMode: RunLoopMode.commonModes)
}
//移除定时器
fileprivate func removeCycleTime(){
//从运行循环中移除
cycleTimer?.invalidate()
cycleTimer = nil
}
//移动到下一个方法
@objc fileprivate func scrollToNext(){
//1.获取当前的偏移量
let currentOffsetX = collectionView.contentOffset.x
let offsetX = currentOffsetX + collectionView.bounds.width
//2.滚动到该位置
collectionView.setContentOffset(CGPoint(x: offsetX, y: 0), animated: true)
}
}
![](https://img.haomeiwen.com/i3245733/508d2df0ea440a3d.png)
添加定时器和移除定时器
![](https://img.haomeiwen.com/i3245733/298dfd716381d55f.png)
对用户拖拽进行特殊处理:
如果是拖拽,移除定时器
如果拖拽完成,添加定时器
![](https://img.haomeiwen.com/i3245733/2708a4e210efcc41.png)
最终效果:
![](https://img.haomeiwen.com/i3245733/ecfc95a287ee4e84.png)
马哥26
网友评论