PK20
PK20

Reputation: 1066

UIAlertController as a common function to access across view controllers

My app validates data received from different view controllers and shows an alert message using UIAlertViewController. It is designed to cater for devices after IOS8. So, no need to worry about UIAlertView handling.

Currently I have my alert handler function (like below) in all the view controllers.

//MARK: Alert handler

func alert(info:String) {
    let popUp = UIAlertController(title: "Alert", message: info, preferredStyle: UIAlertControllerStyle.Alert)
    popUp.addAction(UIAlertAction(title: "OK!", style: UIAlertActionStyle.Default, handler: {alertAction in popUp.dismissViewControllerAnimated(true, completion: nil)}))
    self.presentViewController(popUp, animated: true, completion: nil)
}

I am just wondering if I can have this function written somewhere once and can be shared across the view controllers.

If I am going to have this function in a shared class, is it ok to pass the ViewController instance to the function every time.

Can someone suggest the best way to do this.

Many thanks in advance.

Upvotes: 1

Views: 751

Answers (1)

Tim
Tim

Reputation: 2098

Create a new Swift File.

class AlertMaker {
func alert(info:String, viewController: UIViewController) {
    let popUp = UIAlertController(title: "Alert", message: info, preferredStyle: UIAlertControllerStyle.Alert)
    popUp.addAction(UIAlertAction(title: "OK!", style: UIAlertActionStyle.Default, handler: {alertAction in popUp.dismissViewControllerAnimated(true, completion: nil)}))
    viewController.presentViewController(popUp, animated: true, completion: nil)
}
}

Call in your VC:

AlertMaker().alert("Info to display", self)

Upvotes: 1

Related Questions