美文网首页程序员
用Swift实现无限循环滚动图片

用Swift实现无限循环滚动图片

作者: yahtzee_ | 来源:发表于2016-01-07 16:13 被阅读1840次

    距离期末考试还剩一周半,但是实在不想复习课内的东西。寒假要做个项目,里面可能要用到这种无限循环滚动的视图,正巧平时逛简书的时候收藏了一篇这方面的文章,就拿出来看了看。
    链接在这里:

    iOS图片无限循环解读

    看完他前面的思路,本来想照着他的写一遍的,但是OC基础太差,有些系统的函数还没理解过- - 又觉得看别人代码太累于是乎就打算自己照着思路写写看,顺便检验一下自己现在的水平。

    先看看效果
    loop.gif
    然后我们来说说思路吧。(主要是前面那位童鞋的思路)
    • 创建一个scrollView
    • 把scrollView的contentSize设置为本身宽度的3倍
    • 在scrollView内添加3个ImageView
    接下来就是重点了
    • 第一次初始化的时候我们要把第一个imageView的image设置为我们要滚动的最后一张图片,然后再是第一张和第二张,并把scrollView的contentOffset移到中间那张图的位置
      假设我们有5张图,编号为0 1 2 3 4 那么当前的状态如下图,红框为scrollView,灰色部分为content


      state1.png
    • 然后在每次滚动后我们要做的事是更新3个imageView的image,然后把scrollView的contentOffset改回滚动前的状态,也就是一直显示中间的那个imageView,在这里就是一个屏幕的宽度

    比如我们在前一张图的状态向右滑动,那么当前状态会变成这样

    state2.png

    接着我们要更新3个imageView内的图片

    state3.png

    并且紧接着我们要把contentOffset.x设置为一个scrollView宽度的偏移

    state4.png

    因为前面两步处理起来很快,所以我们是看不到图三的那种状态的,所以在我们看起来就是正常的往后滚动一张图

    下面是这一部分的代码

    private func upade() {
            switch currentPage {
            case 0 ://如果中间页是第一张图片的情况
                (self.scrollView.subviews[0] as! UIImageView).image = images.last
                (self.scrollView.subviews[1] as! UIImageView).image = images[currentPage]
                (self.scrollView.subviews[2] as! UIImageView).image = images[currentPage+1]
            case images.count-1 ://如果中间页是最后一页的情况
                (self.scrollView.subviews[0] as! UIImageView).image = images[currentPage-1]
                (self.scrollView.subviews[1] as! UIImageView).image = images[currentPage]
                (self.scrollView.subviews[2] as! UIImageView).image = images[0]
            default :
                (self.scrollView.subviews[0] as! UIImageView).image = images[currentPage-1]
                (self.scrollView.subviews[1] as! UIImageView).image = images[currentPage]
                (self.scrollView.subviews[2] as! UIImageView).image = images[currentPage+1]
            }
            scrollView.contentOffset = CGPoint(x: self.frame.size.width, y: 0)
        }
    
    我设置了一个currentPage来表示当前所在的页,并且给它添加了属性观察器,然后在scrollView的代理方法里,我们只要监听一下滚动的状态就可以了,是向前滚还是向后滚
    private var currentPage = 0 {
         didSet {
             upade()
             pageControl.currentPage = currentPage
         }
     }
    
    func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
            scrollView.scrollEnabled = true
            if scrollView.contentOffset.x == 0 {                                    //向前滑动
                if currentPage == 0 {
                    currentPage = images.count-1
                } else {
                    currentPage--
                }
            } else if scrollView.contentOffset.x == 2 * self.frame.size.width {     //向后滑动
                currentPage = (currentPage+1)%images.count
            }
        }
    

    要实现自动的滚动也很简单,只要用一个timer就可以实现

    
    func next() {
        scrollView.setContentOffset(CGPoint(x: self.frame.size.width * 2, y: 0), animated: true)
     }
    //开始滚动
    private func startTimer() {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
            self.timer = NSTimer.scheduledTimerWithTimeInterval(self.rollingTime, target: self, selector: "next", userInfo: nil, repeats: true)
            NSRunLoop.currentRunLoop().run()
        }
     }
    //停止滚动
     private func stopTimer() {
        timer!.invalidate()
        timer = nil
     }
    
    我还给scrollView添加了一个单击手势,单击的事件让代理去完成
    weak var delegate: HELoopPageViewDelegate?
    
    private func addGesture() {
            let tap = UITapGestureRecognizer(target: self, action: "tapAction")
            self.scrollView.addGestureRecognizer(tap)
        }
        //让代理来实现具体的点击事件
    func tapAction() {
        delegate?.didSelectPage(currentPage)
    }
    

    下面我们来看一下完整的源代码(好像前面已经贴完大部分的代码了= =)

    import UIKit
    
    protocol HELoopPageViewDelegate: NSObjectProtocol {
        func didSelectPage(pageNum: Int)
    }
    
    enum HEPageControlPosition {
        case MiddleBottom, LeftBottom, RightBottom
        case MiddleTop,    LeftTop,    RightTop
    }
    
    class HELoopPageView: UIView, UIScrollViewDelegate{
    
    //MARK: - 私有属性
        private let scrollView: UIScrollView
        private let pageControl: UIPageControl
        private var images = [UIImage]()
        private var timer: NSTimer?
        private var currentPage = 0 {
            didSet {
                upade()
                pageControl.currentPage = currentPage
            }
        }
        
    //MARK: - 给外部调用的属性
        weak var delegate: HELoopPageViewDelegate?    //点击事件的代理
        var rollingTime: NSTimeInterval = 2.0         //滚动一页的时间
        var rollingEnable: Bool = false {             //是否自动滚动
            willSet {
                if newValue != rollingEnable {
                    if newValue {
                        startTimer()
                    } else {
                        stopTimer()
                    }
                }
            }
        }
        var pageIndicatorColor: UIColor? {                                  //pageControl指示器颜色
            get {
                return pageControl.pageIndicatorTintColor
            }
            set {
                pageControl.pageIndicatorTintColor = newValue
            }
        }
        var currentPageIndicatorColor: UIColor? {                           //pageControl当前页指示器颜色
            get {
                return pageControl.currentPageIndicatorTintColor
            }
            set {
                pageControl.currentPageIndicatorTintColor = newValue
            }
        }
        var pageControlPosion: HEPageControlPosition = .MiddleBottom {      //pageControl位置
            willSet {
                let pw = CGFloat(self.pageControl.numberOfPages) * 17.0
                let w = self.frame.size.width
                let h = self.frame.size.height
                switch newValue {
                case .MiddleBottom:
                    self.pageControl.frame = CGRect(x: (w-pw)/2, y: h-15, width: pw, height: 10)
                case .LeftBottom:
                    self.pageControl.frame = CGRect(x: 0, y: h-15, width: pw, height: 10)
                case .RightBottom:
                    self.pageControl.frame = CGRect(x: w-pw, y: h-15, width: pw, height: 10)
                case .MiddleTop:
                    self.pageControl.frame = CGRect(x: (w-pw)/2, y: 5, width: pw, height: 10)
                case .LeftTop:
                    self.pageControl.frame = CGRect(x: 0, y: 5, width: pw, height: 10)
                case .RightTop:
                    self.pageControl.frame = CGRect(x: w-pw, y: 5, width: pw, height: 10)
                }
            }
        }
        
        
    //MARK: - 初始化方法
        init?(frame: CGRect, let images: [UIImage]) {
    
            self.images = images
            self.scrollView = UIScrollView()
            self.pageControl = UIPageControl()
            super.init(frame: frame)
            if self.images.count < 3 {
                print("init LoopPageView failed")
                return nil
            }
            self.scrollView.frame = CGRect(x: 0, y: 0, width: self.frame.size.width, height: self.frame.size.height)
            self.pageControl.frame = CGRect(x: 0, y: self.frame.size.height-15, width: self.frame.size.width, height: 10)
            self.addSubview(scrollView)
            self.addSubview(pageControl)
            
            self.scrollView.showsHorizontalScrollIndicator = false
            self.scrollView.showsVerticalScrollIndicator = false
            self.scrollView.pagingEnabled = true
            self.scrollView.contentSize = CGSize(width: self.frame.size.width * 3, height: self.frame.size.height)
            self.scrollView.delegate = self
            self.scrollView.contentOffset = CGPoint(x: self.frame.size.width, y: 0)
            
            self.scrollView.addSubview(UIImageView())
            self.scrollView.addSubview(UIImageView())
            self.scrollView.addSubview(UIImageView())
            (self.scrollView.subviews[0] as! UIImageView).image = self.images.last
            (self.scrollView.subviews[1] as! UIImageView).image = self.images[0]
            (self.scrollView.subviews[2] as! UIImageView).image = self.images[1]
            for i in 0..<3 {
                let imgV = self.scrollView.subviews[i] as! UIImageView
                imgV.contentMode = .ScaleAspectFill
                imgV.clipsToBounds = true
                imgV.frame = CGRect(x: CGFloat(i) * self.frame.size.width, y: 0, width: self.frame.size.width, height: self.frame.size.height)
            }
            self.pageControl.numberOfPages = self.images.count
            self.pageControl.enabled = false
            
            self.addGesture()
        }
    
        required init?(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
        
    //MARK: - 点击事件
        private func addGesture() {
            let tap = UITapGestureRecognizer(target: self, action: "tapAction")
            self.scrollView.addGestureRecognizer(tap)
        }
        //让代理来实现具体的点击事件
        func tapAction() {
            delegate?.didSelectPage(currentPage)
        }
        
    //MARK: - 更新imageView中的图片和scrollView内的偏移
        private func upade() {
            switch currentPage {
            case 0 :
                (self.scrollView.subviews[0] as! UIImageView).image = images.last
                (self.scrollView.subviews[1] as! UIImageView).image = images[currentPage]
                (self.scrollView.subviews[2] as! UIImageView).image = images[currentPage+1]
            case images.count-1 :
                (self.scrollView.subviews[0] as! UIImageView).image = images[currentPage-1]
                (self.scrollView.subviews[1] as! UIImageView).image = images[currentPage]
                (self.scrollView.subviews[2] as! UIImageView).image = images[0]
            default :
                (self.scrollView.subviews[0] as! UIImageView).image = images[currentPage-1]
                (self.scrollView.subviews[1] as! UIImageView).image = images[currentPage]
                (self.scrollView.subviews[2] as! UIImageView).image = images[currentPage+1]
            }
            scrollView.contentOffset = CGPoint(x: self.frame.size.width, y: 0)
        }
        
    //MARK: - 自动滚动
        //timer调用使scrollView往下滚动
        func next() {
            scrollView.setContentOffset(CGPoint(x: self.frame.size.width * 2, y: 0), animated: true)
        }
        //开始滚动
        private func startTimer() {
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
                self.timer = NSTimer.scheduledTimerWithTimeInterval(self.rollingTime, target: self, selector: "next", userInfo: nil, repeats: true)
                NSRunLoop.currentRunLoop().run()
            }
        }
        //停止滚动
        private func stopTimer() {
            timer!.invalidate()
            timer = nil
        }
        
    //MARK: - scrollViewDelegate
        //setContentOffset的动画完成后会调用,使currentPage+1
        func scrollViewDidEndScrollingAnimation(scrollView: UIScrollView) {
            currentPage = (currentPage+1)%images.count
        }
        //拖动scrollView时会停止自动滚动
        func scrollViewWillBeginDragging(scrollView: UIScrollView) {
            if rollingEnable {
                stopTimer()
            }
        }
        //停止拖动后会重新开始自动滚动
        func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) {
            if rollingEnable {
                startTimer()
            }
            //在滚动的减速动画没有结束前继续拖动时,因为还没有更新所以边缘是空白,所以在结束拖动时就锁住scrollView,在动画结束后解锁,就可以避免这个问题
            scrollView.scrollEnabled = false
        }
        //拖动scrollView时当减速动画结束时调用
        func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
            scrollView.scrollEnabled = true
            if scrollView.contentOffset.x == 0 {                                    //向前滑动
                if currentPage == 0 {
                    currentPage = images.count-1
                } else {
                    currentPage--
                }
            } else if scrollView.contentOffset.x == 2 * self.frame.size.width {     //向后滑动
                currentPage = (currentPage+1)%images.count
            }
        }
        
        deinit {
            print("deinit")
        }
    }
    
    在外部调用时很简单,我们只要传进去一个UIView的数组即可,当然如果图片小于3张时初始化会失败
    • 最好设置当前controller的automaticallyAdjustsScrollViewInsets属性为true,否则当存在NavigationController的情况下,并且navigationBar的Translucent属性被勾选时,可能会出点小问题,你可以去试一试- -
    • 如果开启了自动滚动,一定要在viewWillDisappear方法里把rollingEnable设为false,否则会内存泄露
    import UIKit
    
    class ViewController2: UIViewController, HELoopPageViewDelegate  {
    
        var loopPage: HELoopPageView!
        override func viewDidLoad() {
            super.viewDidLoad()
            self.view.backgroundColor = UIColor.blackColor()
            self.automaticallyAdjustsScrollViewInsets = false
            
            var images = [UIImage]()
            for i in 1...5 {
                let img = UIImage(contentsOfFile: NSBundle.mainBundle().pathForResource("image\(i)", ofType: "png")!)
                images.append(img!)
            }
            
            loopPage = HELoopPageView(
                frame: CGRectMake(0, 64, self.view.frame.size.width, 150),
                images: images)
            loopPage.delegate = self    //设置代理
            loopPage.pageIndicatorColor = UIColor.grayColor()    //设置pageControl指示器的颜色
            loopPage.currentPageIndicatorColor = UIColor.blackColor()
            loopPage.pageControlPosion = .RightBottom    //设置pageControl的位置
            
            self.view.addSubview(loopPage!)
        }
        
        override func viewDidAppear(animated: Bool) {
            super.viewDidAppear(animated)
            //设置rollingEnable为true即可开启自动滚动功能
            loopPage.rollingEnable = true
        }
        
        override func viewWillDisappear(animated: Bool) {
            //需要在退出前停止自动滚动,否则会内存泄露
            loopPage.rollingEnable = false
        }
        
        //代理方法 点击page时调用
        func didSelectPage(pageNum: Int) {
            print("\(pageNum)")
        }
    
    }
    

    水平有限,学习时间有限,如果我有什么说的不对的或者不好的地方,请联系我!!

    这是第一次写这种技术类的文章,排版啊,内容啊,有什么不好的也请谅解

    谢谢

    相关文章

      网友评论

        本文标题:用Swift实现无限循环滚动图片

        本文链接:https://www.haomeiwen.com/subject/sjefkttx.html