swift3.0 banner轮播图

1.声明一个bannerScrollView,图片数组imageArray, pageControl, 计时器timer

    var bannerScrollView :UIScrollView!
    var imageArray = ["1","2","3","4","5"]
    var pageControl:UIPageControl!
    var  timer:Timer!
  1. 在viewdidload里面写实现方法
        self.setPageControl()
        self.bannerScrollView = self.setBannerSrcrollView(imageArray: imageArray)
        self.view.addSubview(self.bannerScrollView)
        self.setTimerTarget()

3.设置pageControl方法

func  setPageControl() {
        self.pageControl = UIPageControl.init(frame: CGRect.init(x:WIDTH/2-40*scaleWidth, y: 264*scaleWidth, width: 80*scaleWidth, height: 20*scaleWidth))
        self.pageControl.numberOfPages = self.imageArray.count
        self.pageControl.currentPage = 0
        self.pageControl.addTarget(self, action: #selector(self.setPageControlClick), for: .touchUpInside)
        self.view.addSubview(self.pageControl)
    }
    func setPageControlClick() {
        self.timer.invalidate()
        let page = self.pageControl.currentPage
        self.bannerScrollView.scrollRectToVisible(CGRect.init(x: WIDTH*CGFloat(page+1), y: 0, width: WIDTH, height: 200), animated: true)
        self.setTimerTarget()
    }

4.计时器设置

func setTimerTarget() {
        self.timer = Timer.scheduledTimer(timeInterval: 3, target: self , selector: #selector(self.setTimerClick), userInfo: nil, repeats: true)
    }
    func setTimerClick() {
        let page = self.pageControl.currentPage + 1
        if page >= self.imageArray.count {
            self.pageControl.currentPage =  0
            self.bannerScrollView.scrollRectToVisible(CGRect.init(x: WIDTH, y: 0, width: WIDTH, height: 200), animated: false)
        }else {
            self.pageControl.currentPage =  page
            self.bannerScrollView.scrollRectToVisible(CGRect.init(x: WIDTH*CGFloat(page+1), y: 0, width: WIDTH, height: 200*scaleWidth), animated: true)
        }
    }

5.设置scrollview

 func setBannerSrcrollView(imageArray:[String]) -> UIScrollView {
        
        let bannerScrollView = UIScrollView.init(frame: CGRect(x: 0, y: 64, width: WIDTH, height: 200*scaleWidth))
        bannerScrollView.contentSize = CGSize(width: Int(WIDTH)*(imageArray.count+2), height: 64)
        bannerScrollView.showsVerticalScrollIndicator = false
        bannerScrollView.showsHorizontalScrollIndicator = false
        bannerScrollView.isPagingEnabled = true
        bannerScrollView.delegate = self
        for i in 0..

6.切换到其他跟控制器,暂停计时器.
override func viewDidDisappear(_ animated: Bool) {
if self.timer != nil {
self.timer.fireDate = NSDate.distantFuture
}

}
override func viewWillAppear(_ animated: Bool) {
    if self.timer != nil {
        self.timer.fireDate = NSDate.distantPast
    }
    
}
deinit {
    self.timer.invalidate()
}

你可能感兴趣的:(swift3.0 banner轮播图)