原理概述
首先說一下整個banner工具的實現(xiàn)原理闽颇,所用控件主要是UICollectionView,頁碼UIPageControl寄锐,以及計時器Timer兵多。根據(jù)要滾動的數(shù)據(jù)顯示在三個section里面尖啡,每個section都展示所有的數(shù)據(jù),默認看到的是第二個section的某一頁面剩膘,當每次執(zhí)行定時器循環(huán)時先根據(jù)當前顯示的索引以迅雷不及掩耳之勢變?yōu)轱@示第二組的這個頁面衅斩,如果這個頁面是最后一個則下一個頁面就是第三組數(shù)據(jù)的第一個,因此不會導致回滾的尷尬怠褐。
里面使用了isAutoScrolling來判斷是否根據(jù)定時器滾動矛渴,當拖拽時定時器要注銷,使用isAutoScrolling能夠避免定時器與拖拽的沖突
使用
let bannerView = LYAnimateBannerView(frame: CGRect(x: 0, y: 0, width: kScreenW, height: kScreenW), delegate: self)
bannerView.backgroundColor = UIColor.white
bannerView.showPageControl = true
self.bannerView.imageUrlArray = arrM
if arrM.count < 2{
self.bannerView.showPageControl = false
}
源碼
import UIKit
protocol LYAnimateBannerViewDelegate {
func LY_AnimateBannerViewClick(banner:LYAnimateBannerView,index:NSInteger)
}
class LYAnimateBannerView: UIView {
enum LY_BannerType {
case ly_titleType
case ly_imageType
case ly_imageUrlType
}
var LY_AnimateBannerViewClickBlock : ((Int) -> Void)?
var showPageControl = false
fileprivate var delegate : LYAnimateBannerViewDelegate?
fileprivate var collectionView : UICollectionView!
fileprivate var timer : Timer?
fileprivate var type : LY_BannerType = .ly_titleType
fileprivate var pageControl : UIPageControl?
fileprivate var isAutoScrolling = false
var titleArray = Array<String>(){
didSet{
self.type = .ly_titleType
self.setUpCollectionView()
if self.titleArray.count > 1{
self.addTimer()
}
}
}
var imageArray = Array<UIImage>(){
didSet{
self.type = .ly_imageType
self.setUpCollectionView()
if self.imageArray.count > 1{
self.addTimer()
}
}
}
var imageUrlArray = Array<String>(){
didSet{
self.type = .ly_imageUrlType
self.setUpCollectionView()
if self.imageUrlArray.count > 1{
self.addTimer()
}
}
}
init(frame:CGRect,delegate:LYAnimateBannerViewDelegate) {
super.init(frame: frame)
self.frame = frame
self.delegate = delegate
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setUpCollectionView() {
let layout = UICollectionViewFlowLayout()
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = 0
layout.scrollDirection = self.type == .ly_titleType ? .vertical : .horizontal
layout.itemSize = CGSize.init(width: self.w, height: self.h)
self.collectionView = UICollectionView.init(frame: self.bounds, collectionViewLayout: layout)
self.collectionView.dataSource = self
self.collectionView.delegate = self
self.collectionView.backgroundColor = UIColor.clear
self.collectionView.showsVerticalScrollIndicator = false
self.collectionView.showsHorizontalScrollIndicator = false
self.collectionView.isPagingEnabled = true
collectionView.register(UINib.init(nibName: "BannerScrollTitleCell", bundle: Bundle.main), forCellWithReuseIdentifier: "BannerScrollTitleCell")
collectionView.register(UINib.init(nibName: "BannerScrollImageCell", bundle: Bundle.main), forCellWithReuseIdentifier: "BannerScrollImageCell")
self.addSubview(self.collectionView)
self.collectionView.reloadData()
self.setUpPageControl()
}
//set pagecontrol
func setUpPageControl() {
//少于兩個的時候不用滾動
if self.collectionView.numberOfItems(inSection: 0) < 2{
return
}
if self.pageControl != nil{
self.pageControl = nil
self.pageControl?.removeFromSuperview()
}
self.pageControl = UIPageControl()
self.pageControl?.numberOfPages = self.collectionView.numberOfItems(inSection: 0)
self.pageControl?.currentPageIndicatorTintColor = UIColor.darkGray
self.pageControl?.pageIndicatorTintColor = UIColor.lightGray
self.pageControl?.frame = CGRect.init(x: 0, y: self.h - 30, width: self.w, height: 30)
self.addSubview(self.pageControl!)
}
//設(shè)置定時器
func addTimer() {
if self.timer != nil{
self.removeTimer()
}
self.timer = Timer(timeInterval: 3.0, target: self, selector: #selector(LYAnimateBannerView.nextPage), userInfo: nil, repeats: true)
RunLoop.main.add(self.timer!, forMode: .defaultRunLoopMode)
timer!.fire()
self.isAutoScrolling = true
}
//移除定時器
func removeTimer() {
self.timer?.invalidate()
self.timer = nil
}
func nextPage() {
if !self.isAutoScrolling{
return
}
// 1.馬上顯示回最中間那組的數(shù)據(jù)
let currentIndexPathReset = self.resetIndexPath()
// 2.計算出下一個需要展示的位置
var nextItem = currentIndexPathReset.item + 1
var nextSection = currentIndexPathReset.section
if self.type == .ly_titleType{
if nextItem == self.titleArray.count {
nextItem = 0
nextSection += 1
}
}else if self.type == .ly_imageUrlType{
if nextItem == self.imageUrlArray.count {
nextItem = 0
nextSection += 1
}
}else{
if nextItem == self.imageArray.count {
nextItem = 0
nextSection += 1
}
}
let nextIndexPath = IndexPath.init(item: nextItem, section: nextSection)
// 3.通過動畫滾動到下一個位置
if self.type == .ly_titleType{
self.collectionView.scrollToItem(at: nextIndexPath, at: .top, animated: true)
}else{
self.collectionView.scrollToItem(at: nextIndexPath, at: .left, animated: true)
}
self.pageControl?.currentPage = nextItem
}
func resetIndexPath() -> IndexPath {
//current indexpath
guard let currentIndexPath = self.collectionView.indexPathsForVisibleItems.last else{
return IndexPath.init(item: 0, section: 2)
}
//馬上顯示回最中間那組的數(shù)據(jù)
let currentIndexPathReset = IndexPath.init(item: currentIndexPath.item, section: 2)
if self.type == .ly_titleType{
self.collectionView.scrollToItem(at: currentIndexPathReset, at: .top, animated: false)
}else{
self.collectionView.scrollToItem(at: currentIndexPathReset, at: .left, animated: false)
}
return currentIndexPathReset
}
}
extension LYAnimateBannerView : UICollectionViewDelegate, UICollectionViewDataSource{
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 5
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if self.type == .ly_titleType{
return self.titleArray.count
}else if self.type == .ly_imageUrlType{
return self.imageUrlArray.count
}else{
return self.imageArray.count
}
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if self.type == .ly_titleType{
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "BannerScrollTitleCell", for: indexPath) as! BannerScrollTitleCell
if self.titleArray.count > indexPath.row{
cell.titleLbl.text = self.titleArray[indexPath.row]
}
return cell
}else{
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "BannerScrollImageCell", for: indexPath) as! BannerScrollImageCell
if self.type == .ly_imageUrlType{
if self.imageUrlArray.count > indexPath.row{
cell.imgV.kf.setImage(with: URL(string:self.imageUrlArray[indexPath.row]))
}
}else{
if self.imageArray.count > indexPath.row{
cell.imgV.image = self.imageArray[indexPath.row]
}
}
return cell
}
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if self.LY_AnimateBannerViewClickBlock != nil{
self.LY_AnimateBannerViewClickBlock!(indexPath.row)
}else{
self.delegate?.LY_AnimateBannerViewClick(banner: self, index: indexPath.row)
}
}
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
self.removeTimer()
self.isAutoScrolling = false
}
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
let currentIndexPathReset = self.resetIndexPath()
self.pageControl?.currentPage = currentIndexPathReset.item
self.addTimer()
}
}