AlertView using Swift iOS
In this tutorial i am going to discuss how to create AlertView using Swift Language.
Create a new Project
- Select Xcode => File => New Project
- Select Single View Application
- Name your Project
- Save as AlertView Demo
Here we are going to three types of AlertView’s
Create a UserInterface to Show Alerts, here i created three buttons to show three different Alerts.
Alert 1
Create a action for button and show your Alert in the Action
@IBAction func simpleClicked(sender:AnyObject) { let alertController = UIAlertController(title:"Title", message: "A Short Message", preferredStyle: .Alert) // Create the action. let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel) { action in NSLog("The simple alert's cancel action occured.") } // Add the action. alertController.addAction(cancelAction) presentViewController(alertController, animated: true, completion: nil) }
Alert 2
@IBAction func okClicked(sender:AnyObject) { let alertCotroller = UIAlertController(title: "Title", message: "A Short Message", preferredStyle: .Alert) // Create the actions. let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel) { action in NSLog("The \"Okay/Cancel\" alert's cancel action occured.") } let otherAction = UIAlertAction(title: "OK", style: .Default) { action in NSLog("The \"Okay/Cancel\" alert's other action occured.") } // Add the actions. alertCotroller.addAction(cancelAction) alertCotroller.addAction(otherAction) presentViewController(alertCotroller, animated: true, completion: nil) }
Here we can add as many buttons you want in your Alert and provide action for it.
Alert 3
@IBAction func textEntryCllicked(sender:AnyObject) { let alertController = UIAlertController(title: "Alert", message: "A Short Message", preferredStyle: .Alert) // Add the text field for text entry. alertController.addTextFieldWithConfigurationHandler { textField in // If you need to customize the text field, you can do so here. } // Create the actions. let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel) { action in NSLog("The \"Text Entry\" alert's cancel action occured.") } let otherAction = UIAlertAction(title: "OK", style: .Default) { action in NSLog("The \"Text Entry\" alert's other action occured.") } // Add the actions. alertController.addAction(cancelAction) alertController.addAction(otherAction) presentViewController(alertController, animated: true, completion: nil) }
We need to add Textfield to our Alert . if you want to provide a password (secure ) field we need to enable secureTextEntry.
textField.secureTextEntry = true
Add this line into your Textfield method when you are adding it.
Run your Project and see the output…
Here is the Code
The post AlertView using Swift iOS appeared first on iOSAuthor.