swift - 快速覆盖方法

标签 swift overriding

基本上,我目前正在将 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 中的 selftableviewController 会出现在重写的当前函数中是什么?

  • 我应该如何在重写的 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/

相关文章:

ios - 解包可选值 KeyboardWillShow 时意外发现 nil

swift - 打开任何项目时 Xcode 12.4 崩溃

java - 安卓工作室 : @Override "Annotations are not allowed here"

html - 覆盖当前 CSS 以添加一些填充

ruby - 我们可以覆盖 Ruby 中的 true 和 false 方法吗?

swift - 发布图像对象 Clarifai Rest api swift

ios - Swift 文件 - 如何禁用所有警告?

ios - APNS 更改通知消息

laravel - 我如何覆盖 Laravel Nova Controller ?

save - 如何覆盖ckeditor中按钮的处理程序?