iOS 下一款比较暴力的 MVVM 框架

2,672 阅读6分钟
原文链接: github.com

LPDMvvmKit支持 CocoaPods[1],在 Podfile[2]文件中添加如下行

    pod LPDMvvmKit

分为三个Subspecs

LPDMvvmKit/Additions 主要提供一些常用的工具类的代码

    pod LPDMvvmKit/Additions

LPDMvvmKit/Controls 目前提供一些控件,LPDToastView,LPDAlertView可以了解下

    pod LPDMvvmKit/Controls

LPDMvvmKit/Mvvm 就是LPDMvvmKit主要提供的功能了,因为对前两个Subspecs都有依赖,所以使用直接添加以下行就好了

    pod LPDMvvmKit

可以clone并运行,主流程都是有demo可循的。

view controller和view model解耦

目前在github上能搜到的与MVVM相关的Objective-c库有下面几个:

lizelu/MVVM[3]

shenAlexy/MVVM[4]

leichunfeng/MVVMReactiveCocoa[5]

lovemo/MVVMFramework[6]

这些库都不错,都可以了解下,以上这些库各有各的使用场景,因为这些场景未能满足LPDMvvmKit对各层的定义,以及各层之间的分界线,所以这个轮子还得造。

LPDMvvmKit对各层的定义

# 定义
1 Model POCO model[7]
2 View View 或者 ViewController,一般情况下在ViewController中进行View与ViewModel之间的数据绑定,如果View是UITableViewCell和UICollectionViewCell等,也会在View中进行数据绑定
3 ViewModel 维护数据属性(持有Model),维护状态属性,响应用户操作的逻辑(function,RACSignal、RACCommand)
4 Service 这一层提供系统依赖的外部接口,如网络调用层、系统定位等

要让ViewController廋下来的,就需要将对应的业务逻辑移到ViewModel层,要做到并不难,invoke function、subscribe RACSignal、bind RACCommand就可以了,那么问题来了,如何在移到ViewModel层中的业务逻辑中进行页面跳转呢?目前的做法是对导航做了精简,重写导航相关的接口,所有需要push,pop,present,dismiss操作的接口都封装到navigation相关的两个protocol LPDNavigationControllerProtocol[8]LPDNavigationViewModelProtocol[9] 中,当需要present或者push一个view controller,必须要嵌套在navigation view controller中,同样的present或者push一个view model时,必须要嵌套在navigation view model中,这样并不会带来更多的复杂性,但是在需要用navigation时,不需要做任何改动。

更多细节请参考源码,可能不是最好的解决方案,欢迎issue

导航一一对应的例子

  LPDHomeViewModel *vm = [[LPDHomeViewModel alloc] ];
  LPDHomeViewController *vc = [[LPDHomeViewController alloc] initWithViewModel:vm];
  [.navigation lpd_pushViewController:vc animated:];

  LPDHomeViewModel *vm = [[LPDHomeViewModel alloc] ];
  [.navigation pushViewModel:vm animated:];
  [.navigation lpd_popViewControllerAnimated:];

  [.navigation popViewModelAnimated:];
  [.navigation lpd_popToRootViewControllerAnimated];

  [.navigation popToRootViewModelAnimated:];
  LPDHomeViewModel *vm = [[LPDHomeViewModel alloc] ];
  LPDNavigationViewModel *nvm = [[LPDNavigationViewModel alloc] initWithRootViewModel:vm];
  [.navigation lpd_presentViewController:[[LPDNavigationController alloc] initWithViewModel:nvm] animated: completion:];

  LPDHomeViewModel *vm = [[LPDHomeViewModel alloc] ];
  [.navigation presentViewModel:[[LPDNavigationViewModel alloc] initWithRootViewModel:vm] animated: completion:];
  [.navigation lpd_dismissViewControllerAnimated: completion:];

  [.navigation dismissViewModelAnimated: completion:];

子ViewController的例子

要实现子ViewController,现在可以这么做了

    LPDWaybillsViewModel *waybillsViewModel = [[LPDWaybillsViewModel alloc] ];
    waybillsViewModel.title = ;
    waybillsViewModel.waybillStatus = LPDWaybillStatusFetching;
    [ addChildViewModel:waybillsViewModel];
    waybillsViewModel = [[LPDWaybillsViewModel alloc] ];
    waybillsViewModel.title = ;
    waybillsViewModel.waybillStatus = LPDWaybillStatusDelivering;
    [ addChildViewModel:waybillsViewModel];

表单提交的进度条的例子

更简单了,一行代码

  self.submitting = ;  // Show

  self.submitting = ;  // hide

加载的进度条的例子

需要设置beginLodingBlock和endLodingBlock来实现显示和取消加载进度条,然后不需要做其它事情了,剩下的交给框架来实现就好了,后面会说到tableview和collectionview加载的实现

    [ beginLodingBlock:^(UIView *_Nonnull view) {
      UIView *contentView = [view viewWithTag:777777];
       (contentView) {
        return;
      }
      contentView = [[UIView alloc] initWithFrame:view.bounds];
      contentView. = 777777;
      contentView.backgroundColor = [UIColor clearColor];
      [view addSubview:contentView];
      UIView *loadingView = [[UIView alloc] initWithFrame:CGRectMake(, , , )];
      loadingView.layer.cornerRadius = ;
      loadingView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:];

      UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(, , , )];
      imageView.animationImages = @[
        [UIImage imageNamed:],
        [UIImage imageNamed:],
        [UIImage imageNamed:],
        [UIImage imageNamed:],
        [UIImage imageNamed:],
        [UIImage imageNamed:]
      ];
      [loadingView addSubview:imageView];
      imageView.center = CGPointMake(loadingView.width / , loadingView.height / );
      [contentView addSubview:loadingView];
      //      loadingView.center = CGPointMake(contentView.width / 2, contentView.height / 2);

       ([[[UIDevice currentDevice] systemVersion] floatValue] >= ) {
        loadingView.center = [[UIApplication sharedApplication]
                                .keyWindow convertPoint:CGPointMake(UIScreen.width / , UIScreen.height / )
                                                 toView:view];
      }  {
        loadingView.center = CGPointMake([UIApplication sharedApplication].keyWindow.center.,
                                         [UIApplication sharedApplication].keyWindow.center. - );
      }
      [imageView startAnimating];
    }];
    [ endLodingBlock:^(UIView *_Nonnull view) {
      UIView *contentView = [view viewWithTag:777777];
       (contentView) {
        [contentView removeFromSuperview];
      }
    }];

下拉刷新的例子

下拉刷新默认使用MJRefresh,可以扩展然后通过initHeaderBlock来定制自己的下拉刷新效果,要实现下拉刷新不要太简单了,在LPDScrollViewController的子类中添加两行代码,在对应的ViewModel中实现loadingSignal

  self.scrollView = self.tableView;
  self.needLoading = ;

上拉加载更多的例子

上拉加载更多默认使用MJRefresh,目前暂时不支持定制,上拉加载更多的实现也很简单,在LPDScrollViewController的子类中添加一行代码,剩下的就是在对应的ViewModel中实现loadingMoreSignal

  self.needLoadingMore = ;

更多细节请参考demo

data binding

数据绑定是MVVM解藕的根本,前面提到的解决view model和view controller耦合的问题,也是通过ReactiveCocoa的信号流来做到导航同步等。数据绑定的对象有两种,property,collection,这两者的变更能发出通知是数据绑定的必须条件,相对应的在Objective-C中property的变更可以通过KVO实现,当然用RAC的方式更简单了,这里不再阐述。然而collection的变更并没有很好的方式能发出相应的通知,可以扩展相对应的类(如NSMutableArray,NSMutableDictionary等集合类)来达到这类目的。些集合最终是做为UITableView或者UICollectionView的数据源存在,系统框架现在的UITableView和UICollectionView都是通过委托来实现,相关的代码实在繁琐(应该不会只有我一个人这么认为)。我很希望能彻底解决这两个问题,所以有了LPDTableViewModelProtocol[10]LPDCollectionViewModelProtocol[11] 等一系列的代码,主要是为了解决UITableView和UICollectionView的ViewModel的数据绑定并简化相关的代码,实现所需的代码量还是比较多的,有兴趣还是看代码更为直观。 主要是的设计思路是这样的:将增删接口都通过protocol的方式封装,避免每次都是通过delegate去实现,只需要调用对应的接口就好了,另外对一些常用的操作如 didSelect 等都从delegate method改成RACSignal,通过这些改变,让代码可以聚合起来,相关的代码逻辑不需要在多个零散的函数中去添加代码。

demo中的一些例子,加载tableview的数据

-()reloadTable {
   (self.datas && self.datas.count > ) {
    NSMutableArray *cellViewModels = [NSMutableArray array];
     (LPDPostModel *model in self.datas) {
      LPDTablePostCellViewModel *cellViewModel = [[LPDTablePostCellViewModel alloc]initWithViewModel:.tableViewModel];
      cellViewModel.model = model;
      [cellViewModels addObject:cellViewModel];
    }
    [.tableViewModel replaceSectionWithCellViewModels:cellViewModels withRowAnimation:UITableViewRowAnimationTop];
  }{
    [.tableViewModel removeAllSections];
  }
}

添加一个cell

        LPDPostModel *model = [[LPDPostModel alloc]init];
        model.userId = 111111;
        model.identifier = 1003131;
        model.title = First Chapter;
        model.body = GitBook allows you to organize your book into chapters, each chapter is stored in a separate file like this one.;
        LPDTablePostCellViewModel *cellViewModel = [[LPDTablePostCellViewModel alloc]initWithViewModel:.tableViewModel];
        cellViewModel.model = model;
        [.tableViewModel insertCellViewModel:cellViewModel atIndex: withRowAnimation:UITableViewRowAnimationLeft];

批量添加cell

        NSMutableArray *cellViewModels = [NSMutableArray array];
        LPDTableDefaultCellViewModel *cellViewModel1 =
          [[LPDTableDefaultCellViewModel alloc] initWithViewModel:.tableViewModel];
        cellViewModel1.text = ;
        cellViewModel1.detail = 蜂王浆发了;
        cellViewModel1.image = [UIImage imageNamed:];
        [cellViewModels addObject:cellViewModel1];
        LPDTableValue1CellViewModel *cellViewModel2 =
          [[LPDTableValue1CellViewModel alloc] initWithViewModel:.tableViewModel];
        cellViewModel2.text = ;
        cellViewModel2.detail = 蜂王浆发了;
        cellViewModel2.image = [UIImage imageNamed:];
        [cellViewModels addObject:cellViewModel2];
        LPDTableValue2CellViewModel *cellViewModel3 =
          [[LPDTableValue2CellViewModel alloc] initWithViewModel:.tableViewModel];
        cellViewModel3.text = ;
        cellViewModel3.detail = 蜂王浆发了;
        [cellViewModels addObject:cellViewModel3];
        LPDTableSubtitleCellViewModel *cellViewModel4 =
          [[LPDTableSubtitleCellViewModel alloc] initWithViewModel:.tableViewModel];
        cellViewModel4.text = ;
        cellViewModel4.detail = 蜂王浆发了;
        cellViewModel4.image = [UIImage imageNamed:];
        [cellViewModels addObject:cellViewModel4];

        [.tableViewModel insertCellViewModels:cellViewModels atIndex: withRowAnimation:UITableViewRowAnimationLeft];

删除一个cell

        [.tableViewModel removeCellViewModelAtIndex: withRowAnimation:UITableViewRowAnimationRight];

cell的didSelect

      [[[.waybillsTableViewModel.didSelectRowAtIndexPathSignal deliverOnMainThread]
        takeUntil:[ rac_willDeallocSignal]] subscribeNext:^(RACTuple *tuple) {
        @strongify(self);
        __kindof <LPDTableCellViewModelProtocol> cellViewModel = tuple.second;
        LPDWaybillModel *waybillModel = cellViewModel.model;
         (waybillModel.cancelCode == ) {
          LPDWaybillDetailViewModel *detailViewModel = [[LPDWaybillDetailViewModel alloc] ];
          detailViewModel.waybillId = waybillModel.waybillId;
          [.navigation pushViewModel:detailViewModel animated:];
        }
      }];

目前支持的操作

@property (nonatomic, strong, readonly) RACSignal *willDisplayCellSignal;
@property (nonatomic, strong, readonly) RACSignal *willDisplayHeaderViewSignal;
@property (nonatomic, strong, readonly) RACSignal *willDisplayFooterViewSignal;
@property (nonatomic, strong, readonly) RACSignal *didEndDisplayingCellSignal;
@property (nonatomic, strong, readonly) RACSignal *didEndDisplayingHeaderViewSignal;
@property (nonatomic, strong, readonly) RACSignal *didEndDisplayingFooterViewSignal;
@property (nonatomic, strong, readonly) RACSignal *didHighlightRowAtIndexPathSignal;
@property (nonatomic, strong, readonly) RACSignal *didUnhighlightRowAtIndexPathSignal;
@property (nonatomic, strong, readonly) RACSignal *didSelectRowAtIndexPathSignal;
@property (nonatomic, strong, readonly) RACSignal *didDeselectRowAtIndexPathSignal;
@property (nonatomic, strong, readonly) RACSignal *willBeginEditingRowAtIndexPathSignal;
@property (nonatomic, strong, readonly) RACSignal *didEndEditingRowAtIndexPathSignal;

更多关于LPDTableViewModel的可以参看UITableView改造之路[12]

License