一个拆分 TableViewController 的方法

作者: wiilen | 来源:发表于2016-07-19 16:21 被阅读241次

项目中遇到一个情况,一个 tableViewController 中有很多的 section,每个 section 的功能都不太一样,有时候还需要做些条件判断来判断具体应用哪些 section,如果都堆在同一个 tableViewController 中的话,代码会非常多,而且还有一些网络相关的代码。所以打算对整个 controller 进行拆分。

这里拆分的基本思想是,将整个 tableViewController 的 dataSource 和 delegate 分成三个部分:tableViewManager、sectionManager、cellManager。每个部分可以自己处理相关的代理方法,也可以将方法转发给下一级,如 tableViewManager 将 tableview:cellForRowAtIndexPath: 转发给 sectionManager 进行处理。转发处理是默认行为。这三个 manager 类不能直接使用,需要子类化才能使用,等于是三个抽象类。

下面分别来说三个类:
首先是 tableViewManager,这个类需要做一些单独的初始化操作,如对 tableView 进行无主(unowned)引用,方便设置 tableView 的 dataSource 和 delegate 为自己。

  unowned let tableView: UITableView
  
  init(tableView: UITableView)
  {
    self.tableView = tableView
    super.init()
    
    tableView.delegate = self
    tableView.dataSource = self
  }

并且 tableViewManager 中会有一个对 sectionManager 的引用,方便对代理方法进行转发:

  var sectionManagers: [TableViewSectionManager] = []

  func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
  {
    return sectionManagers[safe: indexPath.section]?.tableView(tableView, cellForRowAtIndexPath: indexPath) ?? UITableViewCell()
  }

由于这些抽象类主要用来拆分 tableViewController,所以一般我们不会在 tableViewManager 里面就覆盖代理方法,而是在 sectionManager 中处理该代理方法,而为了方便可能需要在 cellManager 处理的情况,用与上面类似的方法进行转发:

  var cellManagers: [TableViewCellManager] = []
  
  func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
  {
    return cellManagers[safe: indexPath.row]?.tableView(tableView, cellForRowAtIndexPath: indexPath) ?? UITableViewCell()
  }

如果需要的话直接在子类中覆盖就可以了:

  override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
      //configure your cell
  }

如果需要对 cellManager 进行配置,可以初始化一个空的 setionManager,然后把 cellManager 添加进去即可。这里使用 map 能减少一些工作量:

  let itemSectionManager = TableViewSectionManager()
  itemSectionManager.cellManagers = order.items.map { OrderComfirmItemCellManager(item: $0) }
  sectionManagers.append(itemSectionManager)

通过 manager 配置好的 cell 或者 section 需要添加到上一层,最后在 tableViewController 里面初始化 tableManager 就可以了。

总的来说,这个方法对 OC 和 Swift 应该是通用的。这个方法和在 swift 中使用 extension 来实现 protocol 有些不一样,主要是针对一个代理方法可能会变得非常长的情况,如 tableview:cellForRowAtIndexPath: 里面可能需要堆积大量对 section 的判断,或 cell 配置很复杂。

今天早上也看到一篇国外的文章,全面介绍如何拆分 viewController,包括 dataSource、使用 childViewController、把 self.view 的配置移到一个新的 view 的类中去、使用 viewModel、结合 viewModel 的 Binding Pattern(使用 KVO 与 KVC,根据 viewModel 的变化更新 view)等等8个套路,刚刚又重看了一遍,很有收获。

相关文章

网友评论

    本文标题:一个拆分 TableViewController 的方法

    本文链接:https://www.haomeiwen.com/subject/apgmjttx.html