How to show alert controller in swift

UIAlertController Example in Swift

UIAlertController is introduced in iOS 8  and it supports two styles. Using this you can create an alert dialog like UIAlerview or action sheet like UIActionSheet.

1) SIMPLE ALERT DIALOG

Using the below code you can show alert with without any button

let alert = UIAlertController.init(title: "Alert", message: "Thank you using alert controller", preferredStyle: .alert);
self.present(alert, animated: true, completion: nil)

2) SIMPLE ALERT DIALOG WITH ONE BUTTON

Using the below code you can show alert with one button

let alert = UIAlertController.init(title: "Alert", message: "Thank you using alert controller", preferredStyle: .alert);
alert.addAction(UIAlertAction.init(title: "Cancel", style: .cancel, handler: nil))
self.present(alert, animated: true, completion: nil)

3) SIMPLE ALERT DIALOG WITH TWO BUTTONS

Using the below code you can show alert with two buttons with action

let alert = UIAlertController.init(title: "Alert", message: "Thank you using alert controller", preferredStyle: .alert);
alert.addAction(UIAlertAction.init(title: "Delete", style: .default, handler: { (UIAlertAction) in
    //Your Code here
}))
alert.addAction(UIAlertAction.init(title: "Cancel", style: .cancel, handler: nil))
self.present(alert, animated: true, completion: nil)

4) CREATE AN ACTION SHEET WITH 2 ACTIONS

Using the below code you can show actionsheet with two buttons with action

let alert = UIAlertController.init(title: "", message: "Choose Image Source", preferredStyle: .actionSheet);
 
alert.addAction(UIAlertAction.init(title: "Take Photo", style: .destructive, handler: { (UIAlertAction) in
 //Your Code here
}))
 
alert.addAction(UIAlertAction.init(title: "Gallery", style: .default, handler: { (UIAlertAction) in
 //Your Code here
}))
alert.addAction(UIAlertAction.init(title: "Cancel", style: .cancel, handler: nil))
self.present(alert, animated: true, completion: nil)

5) CREATE AN ALERT DIALOG WITH USERNAME AND PASSWORD FIELDS.

To add a text field you can use the method addTextFieldWithConfigurationHandler.
Text fields can be added to only type UIAlertControllerStyleAlert.

let alert = UIAlertController.init(title: "Alert", message: "Enter Your Login Credentials", preferredStyle: .alert);
alert.addTextField { (textField) in
 textField.placeholder = "Username" //for username
}
alert.addTextField { (textField) in
textField.placeholder = "Password" //for Password
 textField.isSecureTextEntry = true
}
alert.addAction(UIAlertAction.init(title: "Login", style: .default, handler: { (UIAlertAction) in
 //Your Code here
}))
 
alert.addAction(UIAlertAction.init(title: "Cancel", style: .cancel, handler: nil))
self.present(alert, animated: true, completion: nil)

You can find Objective C Version here

Reference: Apple Documenation

That’s It. If you like this post, Please comment below or subscribe this blog.

Leave your comments

 

Advertisements