DDMvvm
DDMvvm 是一个 Swift 编写的库,用于想使用 MVVM (模型-视图-视图模型) 框架(Model-View-ViewModel)开始编写 iOS 项目的开发者。
特性
- 为 UIViewController, UIView, UITableViewCell 和 UICollectionCell 提供基类
- 为 ViewModel, ListViewModel 和 CellViewModel 提供基类
- 服务注入
- 为 UINavigationController 和 UIViewController 提供自定义过渡
需求
- iOS 9.0+
- Xcode 9.0+
- Swift 4.0+
依赖
该库依赖于 RxSwift 进行数据绑定和事件处理。如果您对响应式编程不熟悉,建议您先阅读相关内容。除此之外,以下是依赖列表:
安装
CocoaPods 是 Cocoa 项目的依赖管理器。您可以使用以下命令安装它
$ gem install cocoapods
要使用 CocoaPods 在您的 Xcode 项目中集成 DDMvvm,请在您的 Podfile
中指定它
source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '9.0'
use_frameworks!
target '<Your Target Name>' do
pod 'DDMvvm'
end
然后,运行以下命令
$ pod install
示例
要运行示例项目,克隆仓库,然后首先从 Example 目录中运行 pod install
使用
概览
该库主要使用泛型编写,所以请熟悉 Swift 泛型,还有一个非常重要的点,我们无法使用泛型 UIViewController 与 InterfaceBuilder 或 Storyboard 上的 UIViewController 关联。因此,建议使用代码方式,但我们可以继续使用 XIBs 实例化我们的视图(详细信息请查看示例)
库组件
页面、ListPage 和 CollectionPage
在 MVVM 方面,我更倾向于使用 Page 而不是 ViewController
open class Page<VM: IViewModel>: UIViewController, IView, ITransionView
open class ListPage<VM: IListViewModel>: Page<VM>
open class CollectionPage<VM: IListViewModel>: Page<VM>
想法是每个页面将包含一个类型待确定的带有泛型precikenntreologic VM的 ViewModel 属性
View, TableCell 和 CollectionCell
与 页面 类似,View 也是一个泛型 UIView,而 TableCell 和 CollectionCell 是泛型单元格,可以在 ListPage 和 CollectionPage 中使用
open class View<VM: IGenericViewModel>: UIView, IView
open class CollectionCell<VM: IGenericViewModel>: UICollectionViewCell, IView
open class TableCell<VM: IGenericViewModel>: UITableViewCell, IView
它们都具有泛型类型 VM,用于确定其 ViewModel
通过继承 View 或 页面 并实现 2 个主要方法
open func initialize() {}
open func bindViewAndViewModel() {}
然后我们就有了一整套可以绑定到 ViewModel 的视图
ViewModel, ListViewModel 和 CellViewModel
ViewModel 的基类
open class ViewModel<M: Model>: NSObject, IViewModel
open class ListViewModel<M: Model, CVM: IGenericViewModel>: ViewModel<M>, IListViewModel
open class CellViewModel<M: Model>: NSObject, IGenericViewModel
如我们所见,ViewModel 和 CellViewModel 使用一个泛型类型 M(其基于类型为 Model)。此泛型类型用于我们确定每个 ViewModel 的模型类型。ViewModel 和 CellViewModel 的区别在于 ViewModel 包含导航服务,可以帮助我们在应用程序中在不同页面之间导航,而 CellViewModel 则不包含导航服务。ListViewModel 略有不同。它使用另一个泛型类型 CVM,它代表页面中单元格的 ViewModel 类型。另一方面,它包含一个可绑定的项目源数组,可以与列表页或集合页绑定
请查看示例以了解这些基类的详细用法。
服务
库还支持服务注入(适用于单元测试)和一些内置服务,特别是导航服务,这可以帮助我们在页面之间导航。默认情况下,导航服务通过调用注入到页面和 ViewModel 中:
DependencyManager.shared.registerDefaults()
来注册库中所有内置服务(NavigationService、StorageService 和 AlertService)。或者,您也可以创建自己的导航服务并覆盖默认注入。请查看示例以了解设置服务注入的详细步骤。
页面过渡
此库还支持页面过渡,包括导航页面内的页面和模态显示的页面。请参阅实现页面过渡的示例。
许可证
DDMvvm 在MIT许可下可用。有关更多信息,请参阅LICENSE文件。