iOS Swift5从0到1系列(十三):走入 UICollectionView(二):自定义组件(二):轮播图(BannerView)

一、前言

上篇,我们简单了解了 UICollectionView,本篇,我们将基于 UICollectionView 来封装我们的第二个组件:轮播图(BannerView);BannerView 是我们最常见的一种 UI组件,通常,最吸睛的就是它,比如:广告运营、商品活动等,都会使用,是一个核心流量入口。

说起 BannerView 我这里再稍微废话一点 iOS 历史:

  • 曾经,在 iOS 6.0 之前,如果要写一个 BannerView,我们只能用 UIScrollView 来完成(需要自己设计 View 复用);
  • iOS 6.0 之后,有了 UICollectionView (上篇大家如果注意到源码,就应该知道,它实际是继承于 UIScrollView),我们就可以简单的直接用它来开发,系统提供了复用 Cell 的方式,不会担心内存 OOM;

二、轮播图(BannerView)效果

老规矩,正式进入开发之前,我们先来直观看一下效果(程序中的图片来自一个朋友所在的跨境电商公司,直接给找的图,欧美口味):

BannerView.gif

效果如上,一个简单的左右无限轮播图组件。

三、手动创建组件

我们在学习《圆形进度条》组件时,已经和大家聊过,如何使用手动方式创建库,这里我就不再累述,大家忘记了的直接去看之前的文章即可。

当我们创建好之后,并实现了如上功能,在本地集成测试时,当我们将该源码拖入工程中,如果我们有依赖第三方库,这时,Xcode 会自动帮我们去下载,如下图(我们这个 BannerView 依赖了第三方 SDWebImage 库):

local-spm-banner-view.png

我们可以很清楚的看到,拖入组件后,Xcode 会自动分析 Package.swift,当发现我们有依赖第三方时,会去自行下载(比 CocoaPods 智能、方便多了),最主要的是,这几天,咱们大强国开会,Github 简直X了狗了,除非你 VPN。

四、双库支持

同样,我们开发的组件,既要能支持 CocoaPods 也要能支持 SPM,两库配置如下:

4.1、SPM 配置

// swift-tools-version:5.3
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription

let package = Package(
    // 库名
    name: "BannerView",
    
    // 支持的平台列表
    platforms: [.iOS(.v10)],
    
    // 对外支持的功能
    products: [
        .library(name: "BannerView", targets: ["BannerView"]),
    ],
    
    // 外部依赖
    dependencies: [
        // 依赖 SDWebImage
        .package(name: "SDWebImage", url: "https://gitee.com/mirrors/SDWebImage", from: "5.1.0")
    ],

    // 指定源码目录(如果不指定,默认目录名是:Sources/*.*)
    targets: [
        .target(name: "BannerView", dependencies: ["SDWebImage"], path: "Source")
    ],
    
    // 支持的 swift 版本,从 5 开始
    swiftLanguageVersions: [.v5]
)

4.2、CocoaPods 配置

Pod::Spec.new do |s|
  s.name             = 'BannerView'
  s.version          = '1.0.0'
  s.summary          = 'A View Component for CountDown'

  s.description      = <<-DESC
  TODO: Add long description of the pod here.
  DESC

  s.homepage         = 'https://github.com/qingye/ios-swift-demo/BannerView'
  s.license          = { :type => 'MIT', :file => 'LICENSE' }
  s.author           = { '青叶小小' => '24854015@qq.com' }
  s.source           = { :git => 'https://github.com/qingye/ios-swift-demo/BannerView.git', :tag => s.version.to_s }

  s.ios.deployment_target = '10.0'
  s.source_files = 'Source/**/*.swift'
  
  s.dependency 'SDWebImage', '~> 5.0'

end

4.3、源码结构

src-structure.png

源码就两文件,大家一看就知道大致的逻辑与实现。

五、轮波图(BannerView)开发

5.1、Cell 布局

一般 Banner 都是只有图片,偶有文字(有文字的都是新闻类,或者 PC 网页版,APP版很少有),所以,Cell 的布局也就很简单,放一个 UIImageView 即可,代码如下:

class BannerViewCell: UICollectionViewCell {
    var imageView: UIImageView?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        imageView = UIImageView.init(frame: CGRect(x: 0, y: 0, width: frame.width, height: frame.height))
        self.addSubview(imageView!)
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }
}

构造器重载及必要构造器重载,我也在之前的构造器分析中给出过《关键字 designated、convenience、required》,忘记了的大家可以去温习一下。

5.2、View 初始化及 Layout 设置

先定义 BannerPageView 及继承关系,暂时不给出具体代码

public class BannerPageView: UICollectionView, UICollectionViewDelegate, UICollectionViewDataSource {
    ......
}

重写构造器,我们有两种方式,如上面 Cell 那种,直接重载,但还要多写个 required init ,或者,我们可以用扩展(extension),然后写个『便利构造器』,如下:

extension BannerPageView {
    // 便利构造器,调用方只需给出 frame,layout 由该 BannerView 内部实现
    public convenience init(frame: CGRect, loop: Bool) {
        let layout = UICollectionViewFlowLayout()
        ......
        // 必需调用 self.init,详见
        //《iOS Swift5 构造函数分析(一):关键字 designated、convenience、required》
        // https://www.jianshu.com/p/508e27833812
        self.init(frame: frame, collectionViewLayout: layout)
        ......
    }
}

设置 layout

extension BannerPageView {
    // 便利构造器,调用方只需给出 frame,layout 由该 BannerView 内部实现
    public convenience init(frame: CGRect, loop: Bool) {
        let layout = UICollectionViewFlowLayout()
        // 这里是实现轮播,所以统一设置每一个 cell 的宽高
        // 如果想设置每一个 cell 的不同宽高,需要实现 collectionView(_:layout:sizeForItemAt:)
        layout.itemSize = CGSize(width: frame.width, height: frame.height)
        // 水平方向滚动(默认是垂直方向)
        layout.scrollDirection = .horizontal
        // 行最小间距(同一行 item 之间的水平间距)
        layout.minimumLineSpacing = 0
        // 列最小间距(相邻两行同一列 item 之间的垂直间距)
        layout.minimumInteritemSpacing = 0
        
        // 必需调用 self.init,详见
        //《iOS Swift5 构造函数分析(一):关键字 designated、convenience、required》
        // https://juejin.cn/post/6932885089546141709
        self.init(frame: frame, collectionViewLayout: layout)
        ......
    }
}

设置 UICollectionView 的其它属性:委托、数据源、注册 cell 类等

// 仅该文件内变量可见
// 重复使用 cell 的 identifier
fileprivate let kBannerViewCell = "BannerViewCell"

extension BannerPageView {
    // 便利构造器,调用方只需给出 frame,layout 由该 BannerView 内部实现
    public convenience init(frame: CGRect, loop: Bool) {
        ......
        // 自己实现委托
        delegate = self
        // 自己实现数据源
        dataSource = self
        
        // 注册 cell,可以重复使用
        register(BannerViewCell.self, forCellWithReuseIdentifier: kBannerViewCell)
        // 默认背景:白色
        backgroundColor = .white
        // 每一个 item 为一页
        isPagingEnabled = true
        // 不显示水平滚动条
        showsHorizontalScrollIndicator = false
        // 不允许回弹
        bounces = false
    }
}

5.3、暴露对外数据传递方法

public class BannerPageView: UICollectionView, UICollectionViewDelegate, UICollectionViewDataSource {
    fileprivate var urls: [String]?
    
    public func setUrls(_ urls: [String]) {
        // 原始数据:[a, b, c]
        self.urls = urls
        reloadData()
        layoutIfNeeded()
    }
}

只需要 url 数组即可。

5.4、实现 UICollectionViewDataSource 必要方法

public class BannerPageView: UICollectionView, UICollectionViewDelegate, UICollectionViewDataSource {
    // MARK: UICollectionViewDataSource
    public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        urls?.count ?? 0
    }
    
    public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kBannerViewCell, for: indexPath) as! BannerViewCell
    
        let url = urls![indexPath.row]
        // SDWebImage 负责下载并加载图片
        cell.imageView?.sd_setImage(with: URL(string: url), placeholderImage: nil)
        
        return cell
    }
}

5.5、封装 BannerView

import UIKit

public class BannerView: UIView {
    fileprivate var banner: BannerPageView?
    
    public override init(frame: CGRect) {
        super.init(frame: frame)
        
        banner = BannerPageView(frame: frame, loop: true)
        banner?.bannerDelegate = self
        addSubview(banner!)
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }
    
    public func setData(_ urls: [String]) {
        banner?.setUrls(urls)
    }
}

5.6、HomeViewController 引用 BannerView 这里有问题!!!!!!!修改

import UIKit
import BannerView

class HomeViewController: BaseViewController {
    var bannerView: BannerView?
    override func viewDidLoad() {
        super.viewDidLoad()
        ......
        addBannerView()
        ......
    }
    ......
    func addBannerView() {
        bannerView = BannerView(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: 200), loop: true)
        bannerView?.setUrls([
            "https://cdn-1.blushmark.com/blushmark/upimg/c1/ba/8c0793797057964bfa65a210f76a43aafbd1c1ba.gif",
            "https://cdn-1.blushmark.com/blushmark/upimg/d8/bd/3269b7e78582be3d7d17c194cc32fe8b4d48d8bd.jpg",
            "https://cdn-1.blushmark.com/blushmark/upimg/bd/f8/8c836e32bced64eef2a8d916d50081a38819bdf8.jpg"
        ])
        view.addSubview(bannerView!)
    }
}

OK!大家再运行,应该没有任何问题。

六、BannerView 整体源码 & Github

整体源码地址:《传递门》

import UIKit
import SDWebImage

// 仅该文件内变量可见
// 重复使用 cell 的 identifier
fileprivate let kBannerViewCell = "BannerViewCell"

public class BannerPageView: UICollectionView, UICollectionViewDelegate, UICollectionViewDataSource {
    fileprivate var urls: [String]?
    
    public func setUrls(_ urls: [String]) {
        // 原始数据:[a, b, c]
        self.urls = urls
        reloadData()
        layoutIfNeeded()
    }
    
    // MARK: UICollectionViewDataSource

    public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        urls?.count ?? 0
    }
    
    public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kBannerViewCell, for: indexPath) as! BannerViewCell
    
        let url = urls![indexPath.row]
        // SDWebImage 负责下载并加载图片
        cell.imageView?.sd_setImage(with: URL(string: url), placeholderImage: nil)
        
        return cell
    }
}

extension BannerPageView {
    // 便利构造器,调用方只需给出 frame,layout 由该 BannerView 内部实现
    public convenience init(frame: CGRect, loop: Bool) {
        let layout = UICollectionViewFlowLayout()
        // 这里是实现轮播,所以统一设置每一个 cell 的宽高
        // 如果想设置每一个 cell 的不同宽高,需要实现 collectionView(_:layout:sizeForItemAt:)
        layout.itemSize = CGSize(width: frame.width, height: frame.height)
        // 水平方向滚动
        layout.scrollDirection = .horizontal
        // 行最小间距(同一行 item 之间的水平间距)
        layout.minimumLineSpacing = 0
        // 列最小间距(相邻两行同一列 item 之间的垂直间距)
        layout.minimumInteritemSpacing = 0
        
        // 必需调用 self.init,详见
        //《iOS Swift5 构造函数分析(一):关键字 designated、convenience、required》
        // https://www.jianshu.com/p/508e27833812
        self.init(frame: frame, collectionViewLayout: layout)
    
        // 自己实现委托
        delegate = self
        // 自己实现数据源
        dataSource = self
        
        // 注册 cell,可以重复使用
        register(BannerViewCell.self, forCellWithReuseIdentifier: kBannerViewCell)
        // 默认背景:白色
        backgroundColor = .white
        // 每一个 item 为一页
        isPagingEnabled = true
        // 不显示水平滚动条
        showsHorizontalScrollIndicator = false
        // 不允许回弹
        bounces = false
    }
}
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,088评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,715评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,361评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,099评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 60,987评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,063评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,486评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,175评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,440评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,518评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,305评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,190评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,550评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,880评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,152评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,451评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,637评论 2 335

推荐阅读更多精彩内容