Общий класс UIAlertView с возвратом bool в Swift 4 - PullRequest
0 голосов
/ 10 ноября 2019
protocol AlertDelegate: AnyObject {
      func didGetResponse(text: String?)
}
class AlertClass{

    weak var delegate: AlertDelegate?
    static let sharedInstance = AlertClass()
    //Show alert
    func alertWindow(title: String, message: String) {
        DispatchQueue.main.async(execute: {
            let alertWindow = UIWindow(frame: UIScreen.main.bounds)
            alertWindow.rootViewController = UIViewController()
            alertWindow.windowLevel = UIWindow.Level.alert + 1

            let alert2 = UIAlertController(title: title, message: message, preferredStyle: .alert)
            let defaultAction1 = UIAlertAction(title: "Yes", style: .destructive, handler: { action in
                print("Yes")
            })
            let defaultAction2 = UIAlertAction(title: "No", style: .destructive, handler: { action in
                print("No")
            })
            alert2.addAction(defaultAction1)
            alert2.addAction(defaultAction2)

            alertWindow.makeKeyAndVisible()

            alertWindow.rootViewController?.present(alert2, animated: true, completion: nil)



        })
    }
}

Как я могу вернуть значение bool в этом классе?

1 Ответ

0 голосов
/ 11 ноября 2019
class AlertClass{//This is shared class

    weak var delegate: AlertDelegate?
    static let sharedInstance = AlertClass()

    //Show alert
    func alertWindow(title: String, message: String, completion:@escaping (_ result: Bool) -> Void) {
        let alertWindow = UIWindow(frame: UIScreen.main.bounds)
        alertWindow.rootViewController = UIViewController()
        alertWindow.windowLevel = UIWindow.Level.alert + 1

        let alert2 = UIAlertController(title: title, message: message, preferredStyle: .alert)
        let defaultAction1 = UIAlertAction(title: "Yes", style: .destructive, handler: { action in
            completion(true)

        })
        let defaultAction2 = UIAlertAction(title: "No", style: .destructive, handler: { action in
            print("No")
            completion(false)
        })
        alert2.addAction(defaultAction1)
        alert2.addAction(defaultAction2)

        alertWindow.makeKeyAndVisible()

        alertWindow.rootViewController?.present(alert2, animated: true, completion: nil)
    }
}

alert.alertWindow(title: "", message: "Checking Completion") { (result) in
    if result{
        print("It's yes")
    }
    else {
        print("It's no")
    }
}
...