ios - 我应该以 MVP 模式将 View 转换到 iOS 上演示器中的 UIViewController 吗?

标签 ios swift mobile mvp

在 MVP 结构的 iOS 应用程序中,我经常需要在 Presenter 中调用 UIViewController 类中的一些函数。

例如,触发了一个 UI 事件,我的演示者已完成一些业务逻辑并决定执行以下一项或部分 UI 更新

  • 隐藏后退按钮
  • 更新导航栏标题
  • 弹出 UIAlertController

执行以下操作更加容易和整洁

func didClickAButton() {
    //Some business logic
    let vc = mUI as! UIViewController
    vc.navigationItem.hidesBackButton = true
    vc.title = "New Title"
    let alert = UIAlertController(title: "", message: "", preferredStyle: .alert)
    vc.present(alert, animated: true, completion: nil)
}

而不是为我可能需要的 UIViewController 类的每个函数创建一个协议(protocol)函数。

我的问题是处理这个问题的好方法是什么。

编辑: 也许我不清楚我的问题,所以下面的代码应该更好地解释它

protocol ViewProtocol {
    func hideBackButton()
    //Potientially one protocol function for each UIViewController's
    //function I might need
    }

class Presenter {
    weak var mUI: ViewProtocol

    func updateUIAfterSomeLogic() {
        //At this point, I can do
        mUI.hideBackButton()
        //or cast mUI to UIViewController because I know it will always 
        //be a subclass of UIViewController
        let vc = mUI as! UIViewController
        vc.navigationItem.hidesBackButton = true
    }
}

class View: UIViewController, ViewProtocol {
    func hideBackButton() {
        self.navigationItem.hidesBackButton = true
    }
}

最佳答案

您应该向其发送 UIViewController 消息的唯一对象类型是 UIViewController 对象。如果您有其他类型的对象(例如 Presenter),它实现了 UIViewController 的某些方法,但不是 View Controller ,那么您不应该将其转换为 UIViewController。

如果您的 mUI 对象是 UIViewController 的子类,那么它已经一个 UIViewController 并且没有理由将其转换为该类型。

所以不,您发布的代码似乎没有用,如果您的 mUI 对象不是 UIViewController 的子类,那么它不仅没有帮助,而且是一个坏主意.

编辑:

如果mUI始终是ViewController,请使其成为符合您的协议(protocol)的ViewController:

var mUI: UIViewController & ViewProtocol

关于ios - 我应该以 MVP 模式将 View 转换到 iOS 上演示器中的 UIViewController 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51996222/

相关文章:

ios - 如何停止现有的调度队列并开始新的?

ios - 如何在ios swift中从Parse中按降序对NSDate进行排序

ios - iAd插页式广告仅加载一次

ios - 如何创建框架并将其正确使用到 Project Appdelegate 中?在 swift

ios - 如何在 Swift 中从当年的每个月中获取一半

android - 如何从 Android 中的 arrays.xml 中的 <string-item> 列表中获取带有 java 代码的字符串数组?

windows-mobile - 检测移动设备上是否安装了 Compact Framework

c++ - ld : -bind_at_load and -bitcode_bundle (Xcode setting ENABLE_BITCODE=YES) cannot be used together

swift - Moya - 使用 NSOperation 链式请求

android - 是否可以将移动设备用作蜂窝天线以提高移动范围?