【问题标题】:Reusable views/modules with VIPER使用 VIPER 的可重用视图/模块
【发布时间】:2017-09-23 12:28:03
【问题描述】:

我是 VIPER 的新手,正在尝试使用它开发一个模块(1 个屏幕)。应用程序的其他模块中使用了确切的屏幕,但具有一些附加功能。只是想知道我可以在其他模块中重用 VIPER 的哪些组件? 主持人? 路由器? 交互者? 查看?

【问题讨论】:

    标签: ios swift mvvm viper-architecture


    【解决方案1】:

    我正在努力解决同样的问题,更具体地说,我想重用 VIPER 的 View 部分。在我的应用程序中,我有两个模块相同的 ViewController(以 VIPER 术语查看),不同的是操作(在 Presenter 中)。

    到目前为止,我找到了基于父子协议的解决方案(不确定 VIPER 最佳实践在哪里) - 请参阅下面非常简化的示例

    我还建议您查看那里(viper 和协议相关类型):https://stackoverflow.com/a/30325318/5157022

    所以例子。这个类包含我想分享的常用功能

        import UIKit
    
        protocol CommonPresenterProtocol: class {
            func didSelect(row: Int)
        }
    
        protocol CommonViewProtocol: class {
    
        }
    
        class CommonView: UITableViewController {
    
            var presenter: CommonPresenterProtocol?
    
            override func numberOfSections(in tableView: UITableView) -> Int {return 1}
            override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {return 4}
            override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
                return tableView.dequeueReusableCell(withIdentifier: "\(indexPath.row)", for: indexPath)
            }
    
            override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
                presenter?.didSelect(row: indexPath.row)
            }
    
        }
    
        extension CommonView: CommonViewProtocol {
    
        }
    

    然后这是一个类,它采用该功能并添加一些附加功能(请注意,分配“presenter = FirstPresenter()”不应发生在 viewDidLoad - 这只是为了示例而进行的简化)

    import UIKit
    
    protocol FirstViewProtocol: class {
    
    }
    
    protocol FirstPresenterProtocol: CommonPresenterProtocol { //using parent protocol
        func didDeSelect(row: Int) //adding additional functionality
    }
    
    class FirstView: CommonView {
    
        override func viewDidLoad() {
            super.viewDidLoad()
            presenter = FirstPresenter()
        }
    
        override func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
            (presenter as! FirstPresenterProtocol).didDeSelect(row: indexPath.row)
        }
    
    }
    
    extension FirstView: FirstViewProtocol {
    
    }
    

    【讨论】:

      猜你喜欢
      • 2021-11-14
      • 1970-01-01
      • 2018-12-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多