iOS中对瀑布流实现适配器方案

介绍

适配器模式是就是把一种接口转换成另一种接口,统一给调用者提供简单好用的接口。
如上图所示,在工业设计上,苹果电脑为了美观取消了以太网接口,那我们的电脑如果要使用有线以太网,就需要这根线做转接,把USB转成以太网输出,这样苹果电脑就可以上有线网络了。

适配器方案在项目开发中能够大量节约开发和维护成本,Android系统框架中有实现好的适配器方案,对ListView实现的很友好,可以提高对ListView的开发和维护。

我封装了BaseTableViewAdapter和BaseCollectionViewAdapter

在Controller里实现TableView和CollectionView只需要下面这样写

import UIKit

class ViewController: UIViewController {
    
    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var collectionView: UICollectionView!
    
    var cAdapter: MixCollectionViewAdapter?
    var tAdapter: MixTableViewAdapter?

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
        cAdapter = MixCollectionViewAdapter(collectionView)
        cAdapter?.dataSoure = [1, 1, 1, 1, 1, 1, 1]
        
        tAdapter = MixTableViewAdapter(tableView)
        tAdapter?.dataSoure = [1, 1, 1, 1, 1, 1, 1]
    }
}

运行结果如下

发现没有TableView和CollectionView的逻辑只需要写这么点代码。

下面对iOS中UITableView和UICollectionView实现适配器方案。

Swift实现

使用Swift里面实现UITableView的适配器的封装,其中数据声明使用泛型,避免底层参与上层业务逻辑。

UITableView实现

BaseTableViewAdapter

实现BaseTableViewAdapter,基础Adapter,用于继承

class BaseTableViewAdapter<T>: NSObject, UITableViewDelegate, UITableViewDataSource {
    var cellClick:((_ obj:T)->Void)?
    var cellClickIndex:((_ obj:T,_ index:IndexPath)->Void)?
    
    var mTableView:UITableView?
    var mDataSource:[T]?
    var cellHeight:CGFloat = 60
    
    init(_ tableView: UITableView) {
        super.init()
        mTableView = tableView
        mTableView!.dataSource = self
        mTableView!.delegate = self

        onCreate()
    }
    
    var dataSoure:[T] = []{
        willSet{
            mDataSource = newValue
        }
        
        didSet{
            mTableView?.reloadData()
        }
    }
    
    func onCreate() {
        
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        self.mTableView!.deselectRow(at: indexPath, animated: true)
        self.cellClick?(self.mDataSource![indexPath.row])
        self.cellClickIndex?(self.mDataSource![indexPath.row], indexPath)
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.mDataSource?.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return cellHeight
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let data: T = self.mDataSource![indexPath.row]
        return jkTableView(tableView, cellForRowAtIndexPath: indexPath, bingData: data)
    }
    
    func jkTableView(_ tableView: UITableView, cellForRowAtIndexPath indexPath: IndexPath, bingData: T) -> UITableViewCell {
        return UITableViewCell()
    }
    
    func cellOnClick(_ action:@escaping (T) -> Void){
        self.cellClick = action
    }
    
    func cellOnClickIndex(_ action:@escaping (_ obj:T,_ index:IndexPath)->Void){
        self.cellClickIndex = action
    }
    
}

下面讲解代码实现步骤

    init(_ tableView: UITableView) {
        super.init()
        mTableView = tableView
        mTableView!.dataSource = self
        mTableView!.delegate = self

        onCreate()
    }

把UITableView传进来,实现UITableView的代理方法

    var dataSoure:[T] = [] {
        willSet{
            mDataSource = newValue
        }
        
        didSet{
            mTableView?.reloadData()
        }
    }

dataSoure是数据源,调用reloadData,实现TableView代理数据刷新

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        self.mTableView!.deselectRow(at: indexPath, animated: true)
        self.cellClick?(self.mDataSource![indexPath.row])
        self.cellClickIndex?(self.mDataSource![indexPath.row], indexPath)
    }

实现点击,通过block接口传递出去,这样把代理方法通过block传递,此对象实现了大部分的UITableView初始化和代理的逻辑

BaseTableViewAdapter<T>

声明泛型T,前面说了传数据,那我们的数据类型是不固定的,通过泛型我们不需要知道数据类型,因为交给上层去处理就好了。

实现Adapter

前面实现了BaseTableViewAdapter,下面我们利用继承BaseTableViewAdapter,实现业务。

实现MixTableViewAdapter,如下。

class MixTableViewAdapter: BaseTableViewAdapter<Int> {

    override func onCreate() {
        cellHeight = 60
        mTableView?.registerNib(MixVolumeTableViewCell.self)
    }
    
    override func jkTableView(_ tableView: UITableView, cellForRowAtIndexPath indexPath: IndexPath, bingData: Int) -> UITableViewCell {
        let cell: MixVolumeTableViewCell = tableView.dequeueReusableCell(indexPath: indexPath)
        
        //处理data
        //...
        
        return cell
    }
    
}
    override func onCreate() {
        cellHeight = 60
        mTableView?.registerNib(MixVolumeTableViewCell.self)
    }

onCreate里面进行一些TableView的初始化,行高、注册cell等。

    override func jkTableView(_ tableView: UITableView, cellForRowAtIndexPath indexPath: IndexPath, bingData: Int) -> UITableViewCell {
        let cell: MixVolumeTableViewCell = tableView.dequeueReusableCell(indexPath: indexPath)
        
        //处理data
        //...
        
        return cell
    }
class MixTableViewAdapter: BaseTableViewAdapter<Int>

声明泛型类型为Int,处理数据源,通过泛型传递,bingData是泛型传过来的Int。

UICollectionView实现

BaseCollectionViewAdapter

实现BaseCollectionViewAdapter,基础Adapter,用于继承

class BaseCollectionViewAdapter<T>: NSObject, UICollectionViewDelegate, UICollectionViewDataSource {
    
    var cellClick:((_ obj:T)->Void)?
    var mCollectionView: UICollectionView?
    var mDataSource: [T] = [T]()
    
    init(_ collectionView: UICollectionView) {
        super.init()
        
        collectionView.dataSource = self
        collectionView.delegate = self
        
        mCollectionView = collectionView
        onCreate()
    }
    
    func onCreate() {
        
    }

    var dataSoure: [T] = [] {
        willSet {
            mDataSource = newValue
        }
        
        didSet {
            mCollectionView?.reloadData()
        }
    }
    
    // MARK: UICollectionViewDataSource
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return mDataSource.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let data: T = mDataSource[indexPath.item]
        return jkCollectionView(collectionView, cellForItemAt: indexPath, data: data)
    }
    
    func jkCollectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath, data: T) -> UICollectionViewCell {
        return UICollectionViewCell()
    }
    
    // MARK: UICollectionViewDelegate
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        collectionView.deselectItem(at: indexPath, animated: true)
        
        cellClick?(mDataSource[indexPath.item])
    }
    
    func collectionView(_ collectionView: UICollectionView, canMoveItemAt indexPath: IndexPath) -> Bool {
        return false
    }
    
    func collectionView(_ collectionView: UICollectionView, moveItemAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
        
    }

    // MARK: - other
    func cellOnClick(_ action:@escaping (T) -> Void) {
        self.cellClick = action
    }

}

代码讲解

    init(_ collectionView: UICollectionView) {
        super.init()
        
        collectionView.dataSource = self
        collectionView.delegate = self
        
        mCollectionView = collectionView
        onCreate()
    }

传递UICollectionView,实现代理方法

    var dataSoure: [T] = [] {
        willSet {
            mDataSource = newValue
        }
        
        didSet {
            mCollectionView?.reloadData()
        }
    }

传递数据源,刷新CollectionView

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        collectionView.deselectItem(at: indexPath, animated: true)
        
        cellClick?(mDataSource[indexPath.item])
    }

实现点击操作,通过block回调

class BaseCollectionViewAdapter<T>: NSObject, UICollectionViewDelegate, UICollectionViewDataSource

泛型传递

实现Adapter

新建MixCollectionViewAdapter继承BaseCollectionViewAdapter,声明泛型为Int,代码如下。

import UIKit

class MixCollectionViewAdapter: BaseCollectionViewAdapter<Int> {

    override func onCreate() {
        let itemCountOnLine: Int = UIScreen.main.bounds.width > 320 ? 4 : 3
        mCollectionView?.collectionViewLayout = UICollectionViewFlowLayout.flowWithItemOnLine(itemCountOnLine, margin: 12)
    
        mCollectionView?.registerNib(MixItemCollectionViewCell.self)
    }
    
    override func jkCollectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath, data: Int) -> UICollectionViewCell {
        let cell: MixItemCollectionViewCell = collectionView.dequeueReusableCell(indexPath: indexPath)
        
        //处理data
        //...
        
        return cell
    }
}

在onCreate实现CollectionView的进一步初始化

    override func onCreate() {
        let itemCountOnLine: Int = UIScreen.main.bounds.width > 320 ? 4 : 3
        mCollectionView?.collectionViewLayout = UICollectionViewFlowLayout.flowWithItemOnLine(itemCountOnLine, margin: 12)
    
        mCollectionView?.registerNib(MixItemCollectionViewCell.self)
    }

回调处理数据

    override func jkCollectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath, data: Int) -> UICollectionViewCell {
        let cell: MixItemCollectionViewCell = collectionView.dequeueReusableCell(indexPath: indexPath)
        
        //处理data
        //...
        
        return cell
    }

OC实现

因为在OC里面id可以代表一切类型,数据传递可以使用id,运行时直接解析成我们需要的数据类型就可以了。

UITableView实现

BaseTableViewAdapter

OC实现虽有区别,但是大体上是一样的,代码如下。

#import "BaseTableViewAdapter.h"

@implementation BaseTableViewAdapter

- (instancetype)initWithTableView:(UITableView *)tableView {
    if (self = [super init]) {
        _tableView = tableView;
        tableView.delegate = self;
        tableView.dataSource = self;
        [self onCreate];
    }
    
    return self;
}

- (void)onCreate {
    _cellHeight = 64;
}

- (void)setDataSource:(NSArray *)dataSource {
    _dataSource = dataSource;
    
    [_tableView reloadData];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return _cellHeight;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    return [self tableView:tableView cellForObj:_dataSource[indexPath.row]];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForObj:(id)obj {
    return [UITableViewCell new];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:true];
    if (_cellBlock == nil) {
        return;
    }
    _cellBlock(_dataSource[indexPath.row]);
}

@end

初始化TableView,实现代理方法,传递点击事件。

实现Adapter

继承BaseTableViewAdapter,实现业务逻辑,代码如下。

#import "MixTableViewAdapter.h"
#import "MixVolumeTableViewCell.h"

@implementation MixTableViewAdapter

- (void)onCreate {
    self.cellHeight = 60;
    [self.tableView registerNib:[MixVolumeTableViewCell class]];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForObj:(id)obj {
    MixVolumeTableViewCell *cell = [tableView dequeueReusableCell:[MixVolumeTableViewCell class]];
    return cell;
}

@end

实现进一步的初始化操作,可以在此实现cell的业务逻辑。

UICollectionView实现

OC里面UICollectionView的实现逻辑也是大同小异

BaseCollectionViewAdapter
#import "BaseCollectionViewAdapter.h"

@implementation BaseCollectionViewAdapter

- (instancetype)initWithCollectionView:(UICollectionView *)collectionView {
    if (self = [super init]) {
        _collectionView = collectionView;
        collectionView.delegate = self;
        collectionView.dataSource = self;
        [self onCreate];
    }
    
    return self;
}

- (void)onCreate {
    
}

- (void)setDataSource:(NSArray *)dataSource {
    _dataSource = dataSource;
    
    [_collectionView reloadData];
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _dataSource.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    return [self collectionView:collectionView cellForObj:_dataSource[indexPath.item] andIndexPath:indexPath];
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForObj:(id)obj andIndexPath:(NSIndexPath *)indexPath {
    return [UICollectionViewCell new];
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    [collectionView deselectItemAtIndexPath:indexPath animated:YES];
    if (_cellBlock == nil) {
        return;
    }
    _cellBlock(_dataSource[indexPath.item]);
}

@end

传递CollectionView,实现代理方法,传递数据源,刷新数据,传递点击事件。

实现Adapter

继承BaseCollectionViewAdapter,继续业务逻辑,代码如下。

#import "MixCollectionViewAdapter.h"
#import "MixItemCollectionViewCell.h"

@implementation MixCollectionViewAdapter

- (void)onCreate {
    NSInteger itemCountOnLine = [UIScreen mainScreen].bounds.size.width > 320 ? 4 : 3;
    self.collectionView.collectionViewLayout = [UICollectionViewFlowLayout flowLayoutWithItemCountOnLine:itemCountOnLine forMargin:12];
    
    [self.collectionView registerNib:[MixItemCollectionViewCell class]];
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForObj:(id)obj andIndexPath:(nonnull NSIndexPath *)indexPath {
    MixItemCollectionViewCell *cell = [collectionView dequeueReusableCell:[MixItemCollectionViewCell class] forIdp:indexPath];
    cell.bgView.isChecked = YES;
    
    return cell;
}

@end

进一步初始化操作,实现cell的业务逻辑。

总结

iOS中各种MVX模式天天讨论,孰优孰虑?实际上平时的代码中,如果很好的使用设计模式,做代码的解耦,像适配器模式这样很好的使用,代码易读,开发维护成本降低,使用MVC开发绰绰有余了。

本文测试代码放到GitHub上了,有需要可以去查看。

关注我

欢迎关注公众号:jackyshan,技术干货首发微信,第一时间推送。

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

推荐阅读更多精彩内容

  • 1、通过CocoaPods安装项目名称项目信息 AFNetworking网络请求组件 FMDB本地数据库组件 SD...
    X先生_未知数的X阅读 15,937评论 3 118
  • 蒙古人的崛起,是东方在历史上影响世界的最大事件。 忽必烈的元帝国是蒙古帝国的最东的四分之一。虽然从血脉上来说忽必烈...
    haywirehouse阅读 111评论 0 0
  • 飞花逐梦去,何处不京城
    孺鱼阅读 81评论 0 0
  • 1999年12月19日 17时,在澳门警察乐队所奏响的葡国国歌声中,葡国国旗从楼顶的旗杆处降下。随后降旗手将降下的...
    Yanxhan阅读 568评论 0 1
  • 三点: 1、李林老师没有泄题(看教育部和大工的声明) 2、李林老师不参与出题 3、李林老师今年压中的题和考点前几年...
    ALLINMAN阅读 628评论 4 1