美文网首页swift开源库牛叉的demoiOS Developer
swift 轮播图无限滚动 控件的封装

swift 轮播图无限滚动 控件的封装

作者: iOS_愛OS | 来源:发表于2017-08-11 17:57 被阅读300次

    swift 轮播图无限滚动 控件的封装

    轮播图动画1.gif

    这篇文章主要记录自己是怎么一步一步封装一个 轮播图, 记录了整个过程和遇到的一些问题和解决办法.

    我是在 oc 项目中 用swift 写了一个轮播图
    如何在 oc 项目中
    使用 swift 文件 可以看我这篇文章 OC 中 使用 swfit 代码.

    这篇文章给了实现轮播图的四种思路, 嗯, 我选择了使用 collectionView 这个思路

    下面的思路和代码都是来自于 使用 collectionView 实现 无限轮播图

    • 使用 collectionView 实现轮播图

    最初的思路, 创建collectionView 有一个section , section中有 n 个items.
    这里面有个问题, 就是当滑动到最后一个items 时 怎么回到第一个items 实现无限滑动?

    换一种思路, 设置 3 个 section
    默认显示中间那一组(第2组)的 section
    当滑动到 第2组的最后一个 items 时, 再次滚动显示第3组的第一个items
    当在第3组的第一个items 继续往后滚动时, 显示第2组的第2个item , 然后保持在第2组中往后滚动, 直到最后一个items 重复上面的步骤.
    无限滚动代码实现.

    //MARK: - selector event 下一页
        @objc private func nextPage(){
            //print("下一页")
            // 获取当前 inexPath
            let currentIndexPath = self.collectionView?.indexPathsForVisibleItems.last!
            // 获取中间组 indexPath (所有的图片都是最中间的那一组 为主)
            let middleIndexPath = IndexPath(item: (currentIndexPath?.item)!, section: 1)
            
            // 直接显示中间那一组
            collectionView?.scrollToItem(at: middleIndexPath, at: .left, animated: false)
            
            // 要动画挪动的下一个 图片
            var nextItem = middleIndexPath.item + 1
            var nextSection = middleIndexPath.section
            if nextItem==imageUrls?.count{
                // 当最后一张图片时, 要回到第一个图片显示. 这里借用了第二组的第一个 item
                nextItem = 0
                nextSection += 1
            }
            let nextIndexPath = IndexPath(item: nextItem, section: nextSection)
            //pageControl?.currentPage = nextItem
            collectionView?.scrollToItem(at: nextIndexPath, at: .left, animated: true)
        }
    
    • 方法collectionView?.scrollToItem(at: middleIndexPath, at: .left, animated: false) 的理解
    // 这句代码, 要理解 animated 参数, 
    // 当 animated=true 时候, 有动画效果.
    // 当 animated=false , 没有动画效果, 直接就出现 要挪动到的 idnexPath
    collectionView?.scrollToItem(at: middleIndexPath, at: .left, animated: false)
    
    • 关于手动拖动滚动, 有两种方式实现效果.
        1. 使用代理 scrollViewWillEndDragging 这里要做大量的判断才行
    func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
            
            let currentIndexPath = collectionView?.indexPathsForVisibleItems.last
            
            // 防止 手动滑动图片到 第一个或者最后一个 不循环滑动的问题
            
            // 向左滑
            if velocity.x > 0 {
                if currentIndexPath?.section == (maxSections - 1) {
                    let nextIndexPath = IndexPath(item: (currentIndexPath?.item)!, section: 1)
                    collectionView?.scrollToItem(at: nextIndexPath, at: .left, animated: false)
                }
            }else{
                
            // 向右滑
                if currentIndexPath!.section == 0 {
                    let nextIndexPath = IndexPath(item: currentIndexPath!.item, section: 1)
                    collectionView?.scrollToItem(at: nextIndexPath, at: .right, animated: false)
                }
            }
        }
    
     - 2. 使用代理 `scrollViewDidEndDecelerating` 这里只有简单的一句代码就可以实现
    
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
            collectionView?.scrollToItem(at: IndexPath(item: (pageControl?.currentPage)!, section: 1), at: .left, animated: false)
        }
    
    • collectionView的内容向下偏移了一段位移

    百度, 得知, 要在控制器中添加这句代码 self.automaticallyAdjustsScrollViewInsets = NO;
    automaticallyAdjustsScrollViewInsets 默认是 YES 这时候控制器会自动把 [scrollView , tableview, collectionView] 中的内容向自适应挪动一段距离, 这样可以防止遮住 stateBar navigationBar toolBar SearchBar等. 一般我们都是自己管理collectionView的显示范围, 不需要自动调整

    关于 swift 三方库的使用

    • OC项目 中 在swift 文件中 使用 swift 三方库
      直接 import 三方库
      就可以使用

    • OC 项目中 在 oc 文件中 使用 swift 三方库
      要在 oc 项目中 引入文件 三方库名-Swift.h 文件, 这个文件是系统自动生成的.
      这样就可以在 OC 文件中调用 swift 三方库的方法了, 系统会自动把swift 方法映射为 oc 方法.
      不过, 某些swift 特性不能转化为 oc , 故 很多swift 方法不会映射为 oc 方法, 所以有一部分swfit方法 oc 文件不能使用
      更多详细介绍看这篇文章 Swift和Objective-C混编的注意啦

    Snapkit

    swift 中使用自动布局库 Snapkit (跟oc 中的 masonry 用法相似)
    参考文章 Swift编程(六):Snapkit的启示录

    使用过程:
    pod 集成Snapkit : pod 'SnapKit', '~> 3.2.0'

    在oc 自动布局库 masonry 中, 子控件必须全部都加入到父视图之后, 才对每一个子视图进行布局
    在 swift 'Snapkit' 中好像不需要, 加入父视图后, 可以立即进行布局
    ```
    pageControl!.snp.makeConstraints { (make) in
            make.left.right.equalTo(0)
            make.bottom.equalTo(-20)
            make.height.equalTo(30)
        }
    ```
    

    Kingfisher

    开始添加网络图片
    轮播图 , 有个本地默认图片, 和网络加载后的图片
    当网络加载还没有完成时, 显示本地图片, 当网络加载结束后, 用网络图片代替本地图片

    swfit 中 网络图片框架 Kingfisher 竟然是喵神的作品,
    开始学习 Kingfisher 的用法, 先简单的接触, 会加载网络图片就好, 等手头的项目结束后再去仔细读源码

    学习步骤.

    • pod 集成 Kingfisher : pod 'Kingfisher', '~> 3.10.4'

    网络图片素材:
    http://61.144.248.2:8085/carManager/html/ueditor/jsp/upload/info/2017/08/11/pic_1502416479862.jpg
    http://61.144.248.2:8085/carManager/html/ueditor/jsp/upload/info/2017/08/10/pic_1502331229612.jpg
    http://61.144.248.2:8085/carManager/html/ueditor/jsp/upload/info/2017/08/07/pic_1502085582890.jpg
    http://61.144.248.2:8085/carManager/html/ueditor/jsp/upload/info/2017/08/07/pic_1502085108072.jpg
    http://61.144.248.2:8085/carManager/html/ueditor/jsp/upload/info/2017/08/04/pic_1501819284994.jpg
    http://61.144.248.2:8085/carManager/html/ueditor/jsp/upload/info/2017/07/31/pic_1501466845618.jpg

    这里只需要用到 下面的方法就好

    
    cell.bannerImage?.kf.setImage(with: <#T##Resource?#>, placeholder: <#T##Image?#>, options: <#T##KingfisherOptionsInfo?#>, progressBlock: <#T##DownloadProgressBlock?##DownloadProgressBlock?##(Int64, Int64) -> ()#>, completionHandler: <#T##CompletionHandler?##CompletionHandler?##(Image?, NSError?, CacheType, URL?) -> ()#>)
    
    

    这个方法里, 我们只需要传入参数,
    Resource: URL 要缓存的网络图片
    placeholder: UIimage 站位图片
    options: 操作类型 数组 [KingfisherOptionsInfoItem]
    progressBlock(receivedSize, totalSize) 图片下载过程回调
    completionHandler(image,error,type,url) 图片下载完成 回调
    这个方法, 和 SDWebimage 的图片缓存方法差不多.

    • 自定义 初始化方法,
      一直没有走出 OC 的语言区域, 导致自定义初始化方法失败.
      //失败的自定义初始化方法:
      initWithArr(imageArr:[UIImage], titleArr:[String]){
      
      }
      
      // 正确的自定义初始化方法
      convenience init(imageArr:[UIImage], titleArr:[String]){
      
      }
      
    • 轮播图 点击回调事件, 打算用代理来写 逻辑更清晰.
      将点击事件使用代理的方式传递出去.
      注意: swift 中的协议前面需要加上 @objc(协议名字), 如下面的例子, 只有这样才能在 oc 文件中使用该代理
    @objc(BannerViewDelegate)
    public protocol BannerViewDelegate:NSObjectProtocol{
    

    全部封装完毕, 当我们项目需要用到 轮播图模块时 ,只需要把文件引入, 在工程中添加下面的代码就好.

    BannerView *banner = [[BannerView alloc] initWithFrame:frame viewController:self  imageArr:self.imageUrlArr placeHoldImage:placeImage titleArr:self.titleArr];
        [self.view addSubview:banner];
    

    为什么要单独封装 一个轮播器出来呢.

    封装意味着 我的业务逻辑不必被实现细节所污染

    把业务逻辑和功能实现细节分离开. 降低了程序的耦合性.

    demo 暂时先不放出来了, 大家可以自己封装一个玩一玩,
    如果需要救急的话, 私信我, 给你扔demo

    相关文章

      网友评论

        本文标题:swift 轮播图无限滚动 控件的封装

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