AutoCellFactory 0.1.3

AutoCellFactory 0.1.3

测试已测试
语言语言 SwiftSwift
许可证 MIT
发布日期最后发布2016年9月
SPM支持SPM

Oren Rosenblum维护。



  • Oren Rosenblum

AutoCellFactory

AutoCellFactory 基于模型-视图-视图模型 (MVVM) 架构,基本上意味着 cell 拥有一个 ViewModel(称为 presenter),它包含模型,当 AutoCellFactory 设置模型时,presenter 会自动调用 reloadView 并触发 Cell 上的 configureView。一个简单的示意图如下:

configureView 中,cell 通过询问 presenter 需要的字段来配置自身。

示例

要运行示例项目,请克隆仓库,首先从 Example 目录运行 pod install

要求

  • swift 2.1
  • iOS 8.0

安装

AutoCellFactory 通过 CocoaPods 提供。要安装它,只需将以下行添加到 Podfile 中:

pod "AutoCellFactory"

如何使用

通过 Presenter 展示 UITableViewCellModel 示例

您需要添加以下对象:

  • Model - 可以是一个结构体或类,类型不限
  • Presenter - 从 ACBasePresenter<[YOUR MODEL TYPE]> 继承
  • Cell - 从 ACBasicCell 继承
  • xib - 您自定义类的 nib,设置名称和重用标识符为您的 cell 名称

模型

struct SomeModel { 
    var name: String = ""
}

presenter

为您要创建的 cell 创建一个 presenter,它继承自 ACBasePresenter,并带有您的模型作为泛型。在这种情况下 - SomeModel

presenter 是唯一知道模型的对象,并根据此模型提供配置以供 cell 使用。其超类将负责当模型被设置时自动重新加载视图。

必须包含 required init(),这样ACBasicCell就能够自动初始化,而不需要子类进行操作。

class SomeCellPresenter: ACBasePresenter<SomeModel> {
    required init() {}
}

单元格

创建一个ACBasicCell的子类,将你的表示者作为泛型。在这个例子中,是SomeCellPresenter

class SomeCell: ACBasicCell<SomeCellPresenter> {
    override func configureCell() {
        // Do some configuration for your cell
    }
}

泛型类型会保证父类使用此类型初始化表示者,并且在设置模型时自动触发configureCell

刘某

务必为该单元格创建一个Nombre文件,命名应与单元格完全一致,并在相同名称中设置重用标识符。

工厂部分

现在只剩下使用AutoCellFactory来实际显示单元格的操作。

注册

创建AutoCellFactory的实例

lazy var acFactory: AutoCellFactory = AutoCellFactory(tableView: self.tableView, delegate: self.viewModel)

代理需要遵守AutoCellFactoryViewDelegate,并实现该方法

func modelForIndexPath(indexPath: NSIndexPath) -> Any?

在您的AutoCellFactory实例上调用register方法

public func registerForNib(cellsAndModels: [AutoCellFactoryRegistrationType])

传递tableView和一个AutoCellFactoryRegistrationType数组

public typealias AutoCellFactoryRegistrationType = (cellType: ACBasicCellPresenterHolder.Type, modelType: Any.Type)

这样工厂就会知道哪个模型属于每个单元格,例如

acFactory.registerForNib([(SomeCell.self, SomeModel.self)])

然后在cellForRow方法中,只需从acFactory返回单元格即可

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    return acFactory.getCell(forIndexPath: indexPath)
}

就是这样💃

作者

Oren Rosenblum,[email protected]

许可证

AutoCellFactory以MIT许可证提供。有关更多信息,请参阅LICENSE文件。