I wrote a simple function that displays an alert when it is called. I'd like to use this function in several viewControllers. Right now I have the same bit of code copy-pasted into the bottom of each viewController, but I can't help but think there's a better way.
How can one define a function that can be called from any viewController?
Just for reference I'll paste my function below, but this is a general question. I'd like to be able to find an eloquent way to handle keyboard management identically across all view controllers as well.
func displayAlert(title:String, error:String, buttonText: String) {
// Create the alert
var alert = UIAlertController(title: title, message: error, preferredStyle: UIAlertControllerStyle.Alert)
// Add an action
alert.addAction(UIAlertAction(title: buttonText, style: .Default, handler: { action in
// Dismiss when the button is pressed
self.dismissViewControllerAnimated(true, completion: nil)
}))
// Add it to viewController
self.presentViewController(alert, animated: true, completion: nil)
}
question from:
https://stackoverflow.com/questions/27050580/how-are-global-functions-defined-in-swift 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…