在MVP结构化iOS应用程序中,我经常需要在Presenter中的UIViewController类中调用一些函数。
例如,触发UI事件并且我的演示者已完成一些业务逻辑并决定执行以下一个或一些UI更新
执行以下操作会更容易和更整洁
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 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
的某些方法,但不是视图控制器,那么你不应该将它转换为UIViewController
。
如果你的mUI
对象是UIViewController
的子类,那么它已经是UIViewController
并且没有理由将它转换为该类型。
所以不,你发布的代码似乎没用,如果你的mUI
对象不是UIViewController
的子类,那么它不仅无益,这是一个坏主意。
如果mUI始终是ViewController,请将其设置为符合您的协议的ViewController:
var mUI: UIViewController & ViewProtocol