AutoCellFactory
基于模型-视图-视图模型 (MVVM) 架构,基本上意味着 cell 拥有一个 ViewModel
(称为 presenter
),它包含模型,当 AutoCellFactory
设置模型时,presenter 会自动调用 reloadView
并触发 Cell 上的 configureView
。一个简单的示意图如下:
在 configureView
中,cell 通过询问 presenter 需要的字段来配置自身。
要运行示例项目,请克隆仓库,首先从 Example 目录运行 pod install
。
AutoCellFactory 通过 CocoaPods 提供。要安装它,只需将以下行添加到 Podfile 中:
pod "AutoCellFactory"
通过 Presenter
展示 UITableViewCell
的 Model
示例
您需要添加以下对象:
ACBasePresenter<[YOUR MODEL TYPE]>
继承ACBasicCell
继承struct SomeModel {
var name: String = ""
}
为您要创建的 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文件。