Swift UIScrollView滚动视图/无限循环滚动/自动滚动

宋望
2023-12-01

之前用OC写了UIScrollView,这次用Swift写的,写的不好多担待,O(∩_∩)O~

                                        //先签一下协议
class ViewController: UIViewController , UIScrollViewDelegate {
    //Swift没有宏定义,只好定义常量来代替宏定义
    let SCROLL_WIDTH = UIScreen.mainScreen().bounds.width
    let SCROLL_HEIGHT = UIScreen.mainScreen().bounds.height

    var scrollView :UIScrollView?     //轮播图
    var pageC :UIPageControl?         //小点
    var timer :NSTimer?               //定时器
    var scArray :NSMutableArray?      //图片数组
override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        //图片数组
        scArray = ["5.jpg","0.jpg","1.jpg","2.jpg","3.jpg","4.jpg","5.jpg","0.jpg"]

        //初始化轮播图
        scrollView = UIScrollView.init(frame: UIScreen.mainScreen().bounds)
        //ScrollView背景颜色
        scrollView?.backgroundColor = UIColor.cyanColor()
        //ScrollView滚动量
        scrollView?.contentSize = CGSizeMake(SCROLL_WIDTH * CGFloat((scArray?.count)!), SCROLL_HEIGHT)
        //ScrollView偏移量
        scrollView?.contentOffset = CGPointMake(SCROLL_WIDTH, 0)
        //是否按页滚动
        scrollView?.pagingEnabled = true
        //是否显示水平滑条
        scrollView?.showsHorizontalScrollIndicator = false
        //协议
        scrollView?.delegate = self
        self.view.addSubview(scrollView!)

        //遍历图片数组
        for var i = 0 ; i < scArray?.count ; i++ {

            let str :String = (scArray?.objectAtIndex(i))! as! String
            let img = UIImage(named: str)
            //初始化imageView
            let imgV :UIImageView = UIImageView()
            //添加图片
            imgV.image = img
            imgV.backgroundColor = UIColor.lightGrayColor()
            //设置图片位置及大小
            imgV.frame = CGRectMake((CGFloat(i) * SCROLL_WIDTH),0, SCROLL_WIDTH, SCROLL_HEIGHT)
            scrollView?.addSubview(imgV)

            //轻拍手势
            let tap = UITapGestureRecognizer.init(target: self, action: "tapImageV:")
            imgV.tag = 1000 + i
            //打开用户交互
            imgV.userInteractionEnabled = true
            //给图片添加轻拍手势
            imgV.addGestureRecognizer(tap)

        }

        //设置小点的位置大小
        pageC = UIPageControl.init(frame: CGRectMake((SCROLL_WIDTH - 200) / 2, SCROLL_HEIGHT - 50, 200, 50))
        //设置小点背景色
        pageC?.backgroundColor = UIColor.clearColor()
        //设置小点个数
        pageC?.numberOfPages = (scArray?.count)! - 2
        //设置小点当前页码颜色
        pageC?.currentPageIndicatorTintColor = UIColor.whiteColor()
        //设置小点未选中页码颜色
        pageC?.pageIndicatorTintColor = UIColor.grayColor()
        //设置当前选中页
        pageC?.currentPage = 0
        self.view.addSubview(pageC!)

        timer = NSTimer.scheduledTimerWithTimeInterval(3.0, target: self, selector: "change:", userInfo: nil, repeats: true)

    }
    //循环滚动方法
    func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
        //如果图片在第一张的位置
        if scrollView.contentOffset.x == 0 {
            //就变到倒数第二张的位置上
            scrollView.scrollRectToVisible(CGRectMake(scrollView.contentSize.width - 2 * SCROLL_WIDTH,0,SCROLL_WIDTH,SCROLL_HEIGHT), animated: false)
            //如果图片是倒数第一张的位置
        } else if scrollView.contentOffset.x == scrollView.contentSize.width - SCROLL_WIDTH {
            //就变到第二张的位置
            scrollView .scrollRectToVisible(CGRectMake(SCROLL_WIDTH, 0, SCROLL_WIDTH, SCROLL_HEIGHT), animated: false)
        }

        pageC?.currentPage = Int(scrollView.contentOffset.x / SCROLL_WIDTH) - 1

    }
//定时器执行方法
    func change(timer :NSTimer) {

        if pageC?.currentPage == (pageC?.numberOfPages)! - 1 {
            pageC?.currentPage = 0
        } else if (pageC?.currentPage)! < (pageC?.numberOfPages)! - 1 {
            pageC?.currentPage++
        }
        scrollView?.setContentOffset(CGPointMake((CGFloat(pageC!.currentPage + 1)) * SCROLL_WIDTH, 0), animated: false)
    }

    //开启定时器
    func addTimer() {
        timer = NSTimer.scheduledTimerWithTimeInterval(3.0, target: self, selector: "change:", userInfo: nil, repeats: true)
    }

    //关闭定时器
    func removeTimer() {
        timer?.invalidate()
    }

    //开始拖拽时调用
    func scrollViewWillBeginDragging(scrollView: UIScrollView) {
        //关闭定时器
        removeTimer()
    }

    //拖拽结束后调用
    func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        //开启定时器
        addTimer()
    }
    //轻拍事件
    func tapImageV(tap :UITapGestureRecognizer) {

        print((tap.view?.tag)! - 1001)

    }
 类似资料: