之前寫過一篇Swift中的MVC與MVVM
里面說到MVVM目的是為了讓我們的VC減負(fù),不要那么臃腫,但是文章當(dāng)時的實例可以說是一個不完整的MVVM,因為tableView中的代理還是設(shè)置為VC,還是需要VC去做獲取數(shù)據(jù)的操作
為VC減負(fù)最徹底的方法就是將tableView的代理完全分離出去
- 新建一個類去繼承NSObject, UITableViewDataSource, UITableViewDelegate
(這里我直接放到VM里面了)
public class ExpandAndCheckBoxViewModel: NSObject, UITableViewDataSource, UITableViewDelegate
- 完成必要的方法
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: TableViewCell_checkbox = tableView.dequeueReusableCell(for: indexPath)
let section = models[indexPath.section]
let row = section.rows[indexPath.row]
cell.setupCell(model: row)
return cell
}
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return models[section].expand ? models[section].rows.count : 0
}
public func numberOfSections(in tableView: UITableView) -> Int {
return models.count
}
- 將tableView中的代理設(shè)為新建的這個類
private lazy var viewModel = ExpandAndCheckBoxViewModel(delegate: self)
private lazy var tableView: UITableView = {
let tableView = UITableView(frame: UIScreen.main.bounds, style: .plain)
tableView.register(TableViewCell_checkbox.self)
tableView.register(ExpandHeader.self)
tableView.tableFooterView = UIView()
tableView.delegate = viewModel
tableView.dataSource = viewModel
return tableView
}()
- 將VC中原有的相關(guān)代碼刪除
- VC中除了setup UITableView的方法(UITableView DataSource、Delegate都可以從VC中刪除了)
你會發(fā)現(xiàn)VC瞬間少了很多行代碼,實現(xiàn)了VC的瘦身
同樣的方法可以用在UICollectionView里面
希望這篇小小的文章對你有啟發(fā)
這里并不是想分享如何實現(xiàn)這個例子,更多的是想分享架構(gòu)分層的思想
完整項目代碼
如果大家有其他解決方案歡迎留言交流
支持原創(chuàng),版權(quán)所有