ios - VIPER 的可重用 View /模块

标签 ios swift mvvm viper-architecture

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

最佳答案

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

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

我还建议查看那里(viper 和协议(protocol)关联类型):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 {

}

关于ios - VIPER 的可重用 View /模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46379568/

相关文章:

javascript - css webkit column 访问单列

ios - 使用代码执行 Segue 显示黑屏

objective-c - 在加载主应用程序 View 之前获取一些设备信息

objective-c - 在 Swift 中像 Objective-C 一样使用常量

c# - 我无法使用 INotifyPropertyChanged 更新我的值

c# - 防止由于 "PropertyChanged - events"导致的无限循环

ios - Obj-C - POST JSON 数据到服务器?

ios - 没有断点就无法播放音频

ios - 如何从注释中获取属性数据?

wpf - 带有 XML 模型和 LinqToXml 的 MVVM?