基本上,我目前正在将 functionX
添加到我呈现 UIAlertController 的所有地方,如下所示:
let alert = UIAlertController(title: "", message: "", preferredStyle: .alert)
let okAction = UIAlertAction(title: "ok", style: .default)
alert.addAction(okAction)
functionX(actionSheet: alert, controller: self)
self.present(alert, animated: true, completion: nil)
// or it can be
// tableviewController.present(alert, animated: true, completion: nil)
我不想每次都调用 functionX
,而是想覆盖现有方法并在那里调用 functionX
。我尝试了以下操作:
extension UIViewController {
override func present(_ viewControllerToPresent: UIViewController, animated flag: Bool, completion: (() -> Void)? = nil) {
if (viewControllerToPresent is UIAlertController) {
functionX(actionSheet: viewControllerToPresent, controller: /* what should this be? */ )
}
super.present() //error here
}
}
这是一种合适的方法吗?你能帮我填写缺少的参数吗?
即:
Controller 应该是什么?第一个代码 stub 中的
self
或tableviewController
会出现在重写的当前函数中是什么?我应该如何在重写的 present 函数中调用
present
方法?
最佳答案
根据Swift guide ,
Extensions can add new functionality to a type, but they cannot override existing functionality.
因此,您实际上不应该在扩展中覆盖 UIViewController
中的现有方法。
你可以做的是,添加你自己的 present
,称为 functionXAndPresent
:
extension UIViewController {
func functionXAndPresent(_ viewControllerToPresent: UIViewController, animated flag: Bool, completion: (() -> Void)? = nil) {
if (viewControllerToPresent is UIAlertController) {
// to answer your second question, you should use "self" here
functionX(actionSheet: viewControllerToPresent, controller: self)
}
present(viewControllerToPresent, animated: flag, completion: completion)
}
}
你不能通过覆盖来做到这一点,因为你已经发现,你不能真正引用最后的“非覆盖”方法。 super.present
不起作用,因为您在扩展中,而不是子类中。
关于swift - 快速覆盖方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56801870/