UITableView--分離代理為VC瘦身

之前寫過一篇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)所有

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。
禁止轉(zhuǎn)載,如需轉(zhuǎn)載請通過簡信或評論聯(lián)系作者。

友情鏈接更多精彩內(nèi)容