微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决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 举报,一经查实,本站将立刻删除。