W3Schools Learner's Blog

w3Schools programming knowledge summary website

div

12/20/2017

UIAlertController with UITextField and Two Buttons

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

Example:
  1. import UIKit
  2. class ViewController: UIViewController, UITextFieldDelegate  {
  3. override func viewDidLoad() {
  4.     super.viewDidLoad()
  5. var userIdTextField: UITextField?

  6.     // Declare Alert message
  7.     let dialogMessage = UIAlertController(title: "Alert Title", message: "Please provide your ID", preferredStyle: .alert)
  8.     
  9.     // Create OK button with action handler
  10.     let ok = UIAlertAction(title: "OK", style: .default, handler: { (action) -> Void in
  11.         print("Ok button tapped")
  12.         
  13.         if let userInput = userIdTextField!.text {
  14.             print("User entered \(userInput)")
  15.         }
  16.     })
  17.     
  18.     // Create Cancel button with action handlder
  19.     let cancel = UIAlertAction(title: "Cancel", style: .cancel) { (action) -> Void in
  20.         print("Cancel button tapped")
  21.     }
  22.     
  23.     //Add OK and Cancel button to dialog message
  24.     dialogMessage.addAction(ok)
  25.     dialogMessage.addAction(cancel)
  26.     
  27.     // Add Input TextField to dialog message
  28.     dialogMessage.addTextField { (textField) -> Void in
  29.         
  30.         userIdTextField = textField
  31.         userIdTextField?.placeholder = "Type in your ID"
  32.     }
  33.     
  34.     // Present dialog message to user
  35.     self.present(dialogMessage, animated: true, completion: nil)
  36. }
  37. }

No comments:

Post a Comment

Note: only a member of this blog may post a comment.