Swift 中UI委托方法方面的代码优化

问题描述

我被要求优化我的 swift 代码,尤其是在 UI 委托方法方面。

场景:我在五个 UIViewController 中有 UITableView,在每个视图控制器中我都使用 UITableView 委托方法,因为我的代码重复。那么我该如何优化这个东西?

下面是代码结构:可以看到delegate方法代码在重复

class FirstViewController: UITableViewDelegate,UITableViewDataSource {
    
    @IBOutlet weak var tableView: UITableView!
    
    var userArray = [usermodel]()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.delegate = self
        // register cell according to model (Dynamic Cells)
    }
    
    func tableView(_ tableView: UITableView,numberOfRowsInSection section: Int) -> Int {
        return userArray.count
    }
    
    func tableView(_ tableView: UITableView,cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell01",for: indexPath)
        return cell
    }
    
    func tableView(_ tableView: UITableView,didSelectRowAt indexPath: IndexPath) {
        
    }
}

class SecondViewController: UITableViewDelegate,UITableViewDataSource {
    
    @IBOutlet weak var tableView: UITableView!
    
    var productArray = [ProductModel]()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.delegate = self
        // register cell according to model (Dynamic Cells)
    }
    
    func tableView(_ tableView: UITableView,numberOfRowsInSection section: Int) -> Int {
        return productArray.count
    }
    
    func tableView(_ tableView: UITableView,didSelectRowAt indexPath: IndexPath) {
        
    }
}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)