gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 11:13:03 25 4
gpt4 key购买 nike

在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com