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

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

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)")
    }

}

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

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

谢谢

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 157,012评论 4 359
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 66,589评论 1 290
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 106,819评论 0 237
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,652评论 0 202
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 51,954评论 3 285
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,381评论 1 210
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,687评论 2 310
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,404评论 0 194
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,082评论 1 238
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,355评论 2 241
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,880评论 1 255
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,249评论 2 250
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,864评论 3 232
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,007评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,760评论 0 192
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,394评论 2 269
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,281评论 2 259

推荐阅读更多精彩内容