UIAlertController with UITextField and Two Buttons
In this short Swift code example we will create an Alert dialog message with Ok and Cancel buttons as well as one UITextField to let user input their ID.
- Create UIAlertController
- Create OK and Cancel buttons with Action handlers
- Add UITextField to UIAlertController
- Handle OK button action to display text user has entered into UITextField
- import UIKit
- class ViewController: UIViewController, UITextFieldDelegate {
- override func viewDidLoad() {
- super.viewDidLoad()
-
- var userIdTextField: UITextField?
- // Declare Alert message
- let dialogMessage = UIAlertController(title: "Alert Title", message: "Please provide your ID", preferredStyle: .alert)
-
- // Create OK button with action handler
- let ok = UIAlertAction(title: "OK", style: .default, handler: { (action) -> Void in
- print("Ok button tapped")
-
- if let userInput = userIdTextField!.text {
- print("User entered \(userInput)")
- }
- })
-
- // Create Cancel button with action handlder
- let cancel = UIAlertAction(title: "Cancel", style: .cancel) { (action) -> Void in
- print("Cancel button tapped")
- }
-
- //Add OK and Cancel button to dialog message
- dialogMessage.addAction(ok)
- dialogMessage.addAction(cancel)
-
- // Add Input TextField to dialog message
- dialogMessage.addTextField { (textField) -> Void in
-
- userIdTextField = textField
- userIdTextField?.placeholder = "Type in your ID"
- }
-
- // Present dialog message to user
- self.present(dialogMessage, animated: true, completion: nil)
- }
- }
No comments:
Post a Comment
Note: only a member of this blog may post a comment.