用 Swift 实现一个轮播器
2016-06-20 本文已影响329人
没阳光的午后
经常使用别人轮子,或多或少有点问题,打算自己写点轮子,也能提高自己。本轮子使用 swift 实现,注释详细,若有不懂,可联系本人,项目地址
具体实现
该轮播器目前依赖于Kingfisher
和SnapKit
,会在下个版本去掉依赖。
使用了图片数量加一来设置 cell 的数量来完成无缝轮播。
使用懒加载设置主要的 UI:
private lazy var flowLayout: UICollectionViewFlowLayout = {
let flowLayout = UICollectionViewFlowLayout()
flowLayout.minimumLineSpacing = 0
flowLayout.minimumInteritemSpacing = 0
flowLayout.scrollDirection = .Horizontal
return flowLayout
}()
private lazy var collectionView: UICollectionView = {
let collectionView: UICollectionView = UICollectionView(frame: self.bounds, collectionViewLayout: self.flowLayout)
collectionView.delegate = self
collectionView.dataSource = self
collectionView.pagingEnabled = true
collectionView.showsHorizontalScrollIndicator = false
collectionView.showsVerticalScrollIndicator = false
collectionView.registerNib(UINib.init(nibName: "CollectionViewCell", bundle: nil), forCellWithReuseIdentifier: CollectionViewCell.identifier)
return collectionView
}()
private lazy var pageController: UIPageControl = {
let pageController = UIPageControl()
pageController.numberOfPages = self.imageArray.count
pageController.currentPage = 0
pageController.backgroundColor = UIColor.clearColor()
pageController.currentPageIndicatorTintColor = UIColor.whiteColor()
pageController.pageIndicatorTintColor = UIColor.lightGrayColor()
return pageController
}()
/// 添加子视图
private func setupSubview() {
addSubview(collectionView)
addSubview(pageController)
}
添加定时器:
在RunLoop添加定时器时,设置Mode 为NSRunLoopCommonModes,可以在外部控制器滑动时也滚动图片
private func addTimer() {
if imageArray.count == 1 || interval == 0 {
return
}
timer = NSTimer.scheduledTimerWithTimeInterval(self.interval,
target: self,
selector: #selector(changePage),
userInfo: nil,
repeats: true)
NSRunLoop.currentRunLoop().addTimer(timer, forMode: NSDefaultRunLoopMode)
}
图片滚动逻辑:
func scrollViewDidScroll(scrollView: UIScrollView) {
if oldOffset > currentOffset {
// 当前偏移量小于0,滚回最后张图片
if currentOffset < 0 {
collectionView.scrollToItemAtIndexPath(NSIndexPath(forRow: imageArray.count, inSection: 0), atScrollPosition: .None, animated: false)
}
}else {
// 当前偏移量大于 控制器能滚动的距离减去控制器长度,那么滚回第一张图片
if currentOffset > offsetContent - viewLength {
collectionView.scrollToItemAtIndexPath(NSIndexPath(forRow: 0, inSection: 0), atScrollPosition: .None, animated: false)
}
}
// 当最后张图片滑动到第一张时,改变页码
if currentOffset > (CGFloat)(imageArray.count - 1) * viewLength {
pageController.currentPage = 0
}else {
pageController.currentPage = (Int)(currentOffset / viewLength)
}
oldOffset = currentOffset
}
点击 cell,利用代理传出被点击 cell 的 index:
/ 点击 cell 协议
protocol CycleScrollViewDelgate {
func didSelAction(index: Int) -> ()
}
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
delgate?.didSelAction(indexPath.row)
}
具体使用可以查看ViewController.swift文件,如有 BUG 希望大家能反馈。
TODO:
- 去除网络库和图片加载库的依赖
- 能使用本地图片加载数据
- 自定义 pageControll