如何在不重复代码的情况下在所有控制器中显示警报?

Ork*_*ade 2 alert ios appdelegate swift

我想编写一个函数alert()并运行它.但我想在任何控制器中显示此警报而不重复代码.

例如:我有Presence.swift类,这里我有一些条件,如:

if myVar == 1 { // Just for presenting
    runMyAlert()
}
Run Code Online (Sandbox Code Playgroud)

当在后台myVar == 1用户时,无论他在哪里,在哪个屏幕上,他都会在屏幕上获得警报.

如何在不重复代码的情况下完成?我试图在AppDelegate中做到:

func alert(title : String,message : String,buttonTitle : String,window: UIWindow){
    let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)
    alert.addAction(UIAlertAction(title: buttonTitle, style: UIAlertActionStyle.Default, handler: nil))
    window.rootViewController?.presentViewController(alert, animated: true, completion: nil)
}
Run Code Online (Sandbox Code Playgroud)

称之为:

if myVar == 1 {
    AppDelegate().alert()
}
Run Code Online (Sandbox Code Playgroud)

kat*_*000 9

开发Swift你应该知道可以轻松解决问题的协议.您可以创建新协议MyAlert并为UIViewController类创建默认实现.然后只需MyAlert在视图控制器中继承您的协议,您需要它,并调用该函数!

protocol MyAlert {
    func runMyAlert()
}

extension MyAlert where Self: UIViewController {
    func runMyAlert() {
        let alert = UIAlertController(title: title, message: "message", preferredStyle: UIAlertControllerStyle.Alert)
        alert.addAction(UIAlertAction(title: "buttonTitle", style: UIAlertActionStyle.Default, handler: nil))
        self.presentViewController(alert, animated: true, completion: nil)
    }
}
Run Code Online (Sandbox Code Playgroud)

所以你可以实现并调用它:

class MyViewController: UIViewController, MyAlert {
    override func viewDidLoad() {
        runMyAlert() // for test
    }
}
Run Code Online (Sandbox Code Playgroud)

UPD:

您案件的代码:

protocol MyAlert {
    func runMyAlert()
}

extension MyAlert where Self: UIViewController {
    func runMyAlert() {
        let alert = UIAlertController(title: title, message: "message", preferredStyle: UIAlertControllerStyle.Alert)
        alert.addAction(UIAlertAction(title: "buttonTitle", style: UIAlertActionStyle.Default, handler: nil))
        self.presentViewController(alert, animated: true, completion: nil)
    }
}

class OpenChatsTableViewController: UITableViewController, MyAlert, OneRosterDelegate, BuddyRequestProtocol {
    override func viewDidLoad() {
        runMyAlert()
    }
}
Run Code Online (Sandbox Code Playgroud)