swift 设置图片定时手势轮播,scrollview及修改pageControl按钮颜色

首先: 设置使用UIScrollViewDelegate代理协议

其次需要初始化全局变量:

var picArray = [String]()   //图片数量
    let scrollview = UIScrollView()
    let pageControl = UIPageControl()
    var timer = NSTimer()

再次: 设定scrollview 与pageControl 的frame :

接着,循环图片,添加到scrollview中:

for(var i=0;i<self.picArray.count;i++){
                            //show pic scroll
                            let imageVc = UIImageView()
                            let imageX = CGFloat(i*400)
                            imageVc.frame = CGRectMake(imageX, 0, 400, 400)
                            imageVc.image = UIImage(named:picArray[i])
                            self.scrollview.showsHorizontalScrollIndicator = false
                            self.scrollview.addSubview(imageVc)
                         }

再接着设置样式:

self.scrollview.contentSize = CGSizeMake(CGFloat(400*self.picArray.count), 0)
                        self.scrollview.pagingEnabled = true
                        self.scrollview.delegate = self
                        self.mainView.addSubview(self.scrollview)
                        self.pageControl.frame = CGRectMake(270+31, 370+50, 130, 20)
                        self.pageControl.currentPageIndicatorTintColor = UIColor(rgb: 0x288dcd)
                        self.pageControl.pageIndicatorTintColor = UIColor(rgb: 0xd9d9d9)
                        self.pageControl.currentPage = 0
                        self.pageControl.numberOfPages = self.picArray.count
                        self.mainView.addSubview(self.pageControl)
                        self.addTimer()

然后,写scrollview代理函数:

    func scrollViewDidScroll(scrollView: UIScrollView) {
        let scrollviewW =  scrollView.frame.size.width
        var page = Int((scrollview.contentOffset.x + CGFloat( scrollviewW / 2)) / scrollviewW)
        self.pageControl.currentPage = page
    }
    func scrollViewWillBeginDragging(scrollView: UIScrollView) {
        self.removeTimer()
    }
    func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        self.addTimer()
    }

最后增加定时器:

 //开启定时器
    func addTimer(){
        self.timer = NSTimer.scheduledTimerWithTimeInterval(2, target: self, selector: "nextImage", userInfo: nil, repeats: true)
    }
    //关闭定时器
    func removeTimer(){
        self.timer.invalidate()
    }
    func nextImage(){
        var page = Int(self.pageControl.currentPage)
        //println(self.picArray.count)
        if (page == self.picArray.count-1){
            page = 0
        }else{
            page = page+1
        }
        self.scrollview.contentOffset = CGPointMake(CGFloat(page)*self.scrollview.frame.size.width, 0)
    }

 

 

 

参考文章: iOS开发UI篇—UIScrollView控件实现图片轮播

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。