Simple Alert with two buttons in iOS Swift with callback

By | October 27, 2017

Dear Friends,
Today I will show you how to create a simple alert with two buttons and how to write a callback for each button. The code is simple. Its written for Swift 3.

 func showErrorAlert(VC vc : UIViewController, OKTitle okTitle : String, CancelTitle cancelTitle : String, Message message : String, Title title : String) -> Void {
        
        let alertController = UIAlertController(
            title: title,
            message: message,
            preferredStyle: UIAlertControllerStyle.alert
        )
        
        let cancelAction = UIAlertAction(
            title: cancelTitle,
            style: UIAlertActionStyle.destructive) { (action) in
            NotificationCenter.default.post(name: Notification.Name("CancelClicked"), object: nil)
        }
        
        let confirmAction = UIAlertAction(
        title: okTitle, style: UIAlertActionStyle.default) { (action) in
            NotificationCenter.default.post(name: Notification.Name("OKClicked"), object: nil)
        }
        
        alertController.addAction(confirmAction)
        alertController.addAction(cancelAction)
        
        vc.present(alertController, animated: true, completion: nil)
    }

Send your comments to coderzheaven@gmail.com

Leave a Reply

Your email address will not be published. Required fields are marked *