Want to add an action to a UIAlertView button using Swift iOS? The Swifty way is to use the new UIAlertController and closures:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | // Create the alert controller let alertController = UIAlertController(title: "Title", message: "Message", preferredStyle: .Alert) // Create the actions let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default) { UIAlertAction in NSLog("OK Pressed") } let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel) { UIAlertAction in NSLog("Cancel Pressed") } // Add the actions alertController.addAction(okAction) alertController.addAction(cancelAction) // Present the controller self.presentViewController(alertController, animated: true, completion: nil) |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | // Create the alert controller let alertController = UIAlertController(title: "Title", message: "Message", preferredStyle: .alert) // Create the actions let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default) { UIAlertAction in NSLog("OK Pressed") } let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel) { UIAlertAction in NSLog("Cancel Pressed") } // Add the actions alertController.addAction(okAction) alertController.addAction(cancelAction) // Present the controller self.present(alertController, animated: true, completion: nil) |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.