// // MPTableManager.swift // MusicPlayer // // Created by Mr.Zhou on 2024/4/7. // import UIKit ///tableViewCell配置闭包(index-索引路径,tableView-当前表格,在VC中实现cell实体) typealias TableViewCellConfigureBlock = (_ index:IndexPath, _ tableView:UITableView) -> UITableViewCell ///tableViewCell点击闭包(index-索引路径,tableView-当前表格,在VC中实现点击方法) typealias TableViewCellDidSelectBlock = (_ index:IndexPath, _ tableView:UITableView) -> Void ///tableView通用控制器 class MPTableManager:NSObject { ///包含组行的数据组 private var sectionAndItems:[[Any]]? ///cell注册id组(与数据组组数相同) private var cellIdentifiers:[String]? //配置闭包 private var configureCellBlock:TableViewCellConfigureBlock! //选中闭包 private var didSelectBlock:TableViewCellDidSelectBlock? /// 自定义UITableView控制器初始化方法 /// - Parameters: /// - sectionItems: 包含组行的二维数组数据 /// - cellIdentifier: cell注册ID组(与sectionItems中的组数相同) /// - configureCellBlock: cell配置闭包 /// - didSelectBlock: cell点击事件闭包 init(_ sectionItems: [[Any]]?, cellIdentifiers: [String]?, configureCellBlock: TableViewCellConfigureBlock?, didSelectBlock: TableViewCellDidSelectBlock?) { super.init() self.sectionAndItems = sectionItems self.cellIdentifiers = cellIdentifiers self.configureCellBlock = configureCellBlock self.didSelectBlock = didSelectBlock } //获取索引指定的数据 private func item(_ indexPath: IndexPath) -> Any? { if let items = sectionAndItems?[indexPath.section] { return items[indexPath.row] }else { return nil } } //为tableView注册delegate,datasource,以及cell,自适应高度 func handleTableViewDataSourceAndDelegate(_ tableView: UITableView?, rowHeight:CGFloat = 0) { guard let table = tableView else { print("TableView is null") return } table.dataSource = self table.delegate = self table.rowHeight = rowHeight != 0 ? rowHeight:UITableView.automaticDimension table.estimatedRowHeight = 200 guard cellIdentifiers != nil else { return } cellIdentifiers!.forEach { item in //判断未注册 guard table.dequeueReusableCell(withIdentifier: item) == nil else { return } //判断是否存在nib文件 if let _ = Bundle.main.path(forResource: item, ofType: "nib") { //nib注册 table.register(.init(nibName: item, bundle: nil), forCellReuseIdentifier: item) }else { //cell注册 table.register(item.classFromString().self, forCellReuseIdentifier: item) } } } } //MARK: - tableView的实现 extension MPTableManager:UITableViewDataSource, UITableViewDelegate { //返回组 func numberOfSections(in tableView: UITableView) -> Int { guard sectionAndItems != nil else { return 0 } return sectionAndItems!.count } //返回行 func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { guard let items = sectionAndItems?[section] else { return 0 } return items.count } //实现cell func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = configureCellBlock(indexPath, tableView) return cell } //点击事件 func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { guard didSelectBlock != nil else { return } didSelectBlock!(indexPath, tableView) } }