在所有视图控制器中创建警报功能-迅速 [英] create alert function in all view controllers - swift

查看:72
本文介绍了在所有视图控制器中创建警报功能-迅速的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试声明一个用于在我的应用中显示警报的函数.为了避免重复工作,我正在尝试对所有应用程序使用相同的功能.我试图通过创建带有函数showNotification的类来做到这一点.但是当我创建该类的对象并调用该方法时,什么也没发生.我该怎么办?

I'm trying to declare a function for showing alerts in my app. To avoid repeating work, i'm trying to use same function for all my app. I tried to do that by creating a class with function showNotification. but when i create an object of that class and call the method, nothing happens. How can i do that?

class SharedPropertiesAndMetods : UIViewController {

    func showNotification(title: String, message: String)
    {
        let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
        let defaultAction = UIAlertAction(title: "تائید", style: .default, handler: nil)
        alertController.addAction(defaultAction)
        present(alertController, animated: true, completion: nil)
    }

}

推荐答案

我要做的是创建一个通用"视图控制器来完成工作并从中继承:

What I would do is to create a 'generic' view controller that do the job and than inherit from it:

1.如果您希望每次显示视图时都显示警报,则:

class GenericViewController: UIViewController {

    // MARK: - View lifecycle -

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        if let notification = self.shouldDisplayAlertNotification() {
            self.showNotification(notification)
        }
    }

    // MARK: - Internal methods -

    func shouldDisplayAlertNotification() -> AlertNotification? {
        return nil
    }

    // MARK: - Private methods -

    private func showNotification(_ alertNotification: AlertNotification) {
    }

}

class MyController: GenericViewController {

    override func shouldDisplayAlertNotification() -> AlertNotification? {
        return AlertNotification(title: "Title", message: "Message")
    }

}

其中AlertNotification是您的自定义模型类:

Where AlertNotification is your custom model class:

class AlertNotification {
    var title: String
    var message: String

    init(title: String, message: String) {
        self.title = title
        self.message = message
    }
}

通过这种方式,只有覆盖shouldDisplayAlertNotification的VC才会显示警报.

In this way, only VC that overrides shouldDisplayAlertNotificationwill display alert.

2.如果要在需求"上显示警报:

根据建议,扩展UIViewController

As suggested, extend UIViewController

extension UIViewController {
    func showNotification(title: String, message: String) {
    }
}

这篇关于在所有视图控制器中创建警报功能-迅速的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆