美文网首页iOS 基础开发 小知识收集iOS高阶UI相关
一行代码(两张图片)搞定简单轮播(Swift版)

一行代码(两张图片)搞定简单轮播(Swift版)

作者: 白小西与黑小南 | 来源:发表于2016-05-11 08:41 被阅读2283次

最近开始学习Swift,想将公司从OC转移到这上面来,毕竟Swift发展势头迅猛。于是想将公司原有经常用的UI及工具控件重新写一遍,有利于自己对Swift的了解!

效果图如下

demo.gif

使用代码

 let imgArray = [
            "http://www.netbian.com/d/file/20150519/f2897426d8747f2704f3d1e4c2e33fc2.jpg",
            "http://www.netbian.com/d/file/20130502/701d50ab1c8ca5b5a7515b0098b7c3f3.jpg",
            NSURL(string: "http://www.netbian.com/d/file/20110418/48d30d13ae088fd80fde8b4f6f4e73f9.jpg")!,
            UIImage(named: "carouse_1")!,
            UIImage(named: "carouse_2")!,
            UIImage(named: "carouse_3")!
        ]
        self.silenceCarouselView = SilenceCarouselView(
            frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.size.width, 200), 
            imageArray: imgArray, 
            silenceCarouselViewTapBlock: { (carouselView, index) in
                      print(index)
        });

结构

此轮播效果实现的结构如下:

轮播结构.png

UIView两个子View:UIScrollView、UIPageControl
UIScrollView两个子UIImageView

原理

UIScrollView的宽度:width
UIScrollView的高度:height
两个UIImageView: currentImgView、otherImgView,并且他们的宽高与UIScrollView的宽高相等

UIScrollview:

scrollview的ContentSzie.png
// 设置内容宽度为3倍的尺寸
self.scrollView?.contentSize = CGSizeMake(self.bounds.size.width * 3, self.bounds.size.height)

两个UIImageView的位置:

两个UIImageView的位置.png
// 设置显示的位置
self.scrollView?.contentOffset = CGPointMake(self.bounds.size.width, 0)

左右滑动时改变otherImgView的frame属性让其分别移至currentImgView的左或右两端,并设置图片,滑动结束后交换两张图片的内容并设置重置UIScrollview的滚动位置

 /**
     定义手指滑动方向枚举
     
     - DirecNone:  没有动
     - DirecLeft:  向左
     - DirecRight: 向右
     */
    enum CarouselViewDirec {
        case DirecNone
        case DirecLeft
        case DirecRight
    }


// 监听scrollView滚动事件
public func scrollViewDidScroll(scrollView: UIScrollView) {
        // 设置手指滑动方向
        self.currentDirec = scrollView.contentOffset.x > scrollView.bounds.size.width ? .DirecLeft : .DirecRight;
        // 向右滑
        if self.currentDirec == .DirecRight {
            // 将其他图片显示到左边
            self.otherImgView!.frame = CGRectMake(0, 0, scrollView.bounds.size.width, scrollView.bounds.size.height);
            // 下一索引-1
            self.nextIndex = self.currIndex - 1
            // 当索引 < 0 时, 显示最后一张图片
            if self.nextIndex < 0 {
                self.nextIndex = self.imageArray!.count - 1
            }
        }
        // 向左滑动
        else if self.currentDirec == .DirecLeft {
             // 将其他图片显示到右边
            self.otherImgView!.frame = CGRectMake(CGRectGetMaxX(self.currentImgView!.frame), 0, scrollView.bounds.size.width, scrollView.bounds.size.height);
            // 设置下一索引
            self.nextIndex = (self.currIndex + 1) % self.imageArray!.count
        }
        // 去加载图片
        self.loadImg(self.otherImgView!, index: self.nextIndex)
    }

 /**
     设置整个轮播图片的显示逻辑
     */
    private func reloadImg() -> (){
        self.currentDirec = .DirecNone;//清空滚动方向
        //判断最终是滚到了右边还是左边
        let index = self.scrollView!.contentOffset.x / self.scrollView!.bounds.size.width;
        //等于1表示最后没有滚动,返回不做任何操作
        if index == 1 {return}
         //当前图片索引改变
        self.currIndex = self.nextIndex;
        self.pageControl!.currentPage = self.currIndex
        // 将当前图片的位置放到中间
        self.currentImgView!.frame = CGRectMake(self.scrollView!.bounds.size.width, 0, self.scrollView!.bounds.size.width, self.scrollView!.bounds.size.height)
        // 将其他图片对象的图片给当前显示的图片
        self.currentImgView!.image = self.otherImgView!.image
        // 设置视图滚到中间位置
        self.scrollView!.contentOffset = CGPointMake(self.scrollView!.bounds.size.width, 0)
    }
    
    /**
     加载图片
     
     - parameter imgView: 需要加载图片的 UIImageView
     - parameter index:   加载图片的索引
     */
    private func loadImg(imgView:UIImageView,index:Int){
        let imgData = self.imageArray![index]
        // 如果是字符串类型,就去拼接URL
        if imgData is String {
            // MARK: - 此处可以换成别的网络图片加载逻辑
            imgView.kf_setImageWithURL(NSURL(string: imgData as! String)!, placeholderImage: nil)
        }
        // 如果是NSURL类型则直接去加载
        else if imgData is NSURL {
            // MARK: - 此处可以换成别的网络图片加载逻辑
            imgView.kf_setImageWithURL(imgData as! NSURL, placeholderImage: nil)
        }
        // 图片类型
        else if imgData is UIImage {
            imgView.image = imgData as? UIImage
        }
        // 其他未找到为空
        else{
            imgView.image = nil
        }
    }

至此已经实现图片无限滚动,接下来实现自动轮播

 /**
     初始化计时器
     */
    private func initTimer() -> (){
        //如果只有一张图片,则直接返回,不开启定时器
        if self.imageArray!.count <= 1 {
            return
        }
        //如果定时器已开启,先停止再重新开启
        if timer != nil {
            timer?.invalidate()
        }
        timer = NSTimer.scheduledTimerWithTimeInterval(self.time, target: self, selector: #selector(SilenceCarouselView.timerFunction), userInfo: nil, repeats: true)
        //        timer?.fire()
        NSRunLoop.currentRunLoop().addTimer(self.timer!, forMode: NSDefaultRunLoopMode)

    }
    
    /**
     定时调用的方法
     */
    func timerFunction() -> (){
        //动画改变scrollview的偏移量就可以实现自动滚动
        self.scrollView?.setContentOffset(CGPointMake(self.scrollView!.bounds.size.width * 2, 0), animated: true)
    }

//MARK: - UIScrollView代理方法
    
    public func scrollViewWillBeginDragging(scrollView: UIScrollView) {
        // 开始拖动时停止自动轮播
        self.timer?.invalidate()
    }
    
    public func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        // 结束拖动时开启自动轮播
        self.initTimer()
    }
    
    public func scrollViewDidEndScrollingAnimation(scrollView: UIScrollView) {
        // 带动画的设置scrollview位置后会调用此方法
        self.reloadImg() // 设置图片
    }
    
    
    public func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
        // 结束滚动时重置方向
        self.currentDirec = .DirecNone
        // 设置图片
        self.reloadImg()
    }

以上就是大概的原理逻辑代码,如需要源码请查看Demo-github

我只想实现最简单的功能,因为这样方便日后的扩展修改,当封装的东西越多,你想改的难度和时间成本就越高,所有我就从简了! (如果你想实现更多的功能,把代码拿走,你的代码你做主!)

1、参考资料:高效图片轮播,两个ImageView实现(来自:推酷)
2、轮播控件中用到的第三方框架:onevcat 的 Kingfisher 网路图片加载框架

相关文章

网友评论

  • yxnne:不错不错 学习了

本文标题:一行代码(两张图片)搞定简单轮播(Swift版)

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