UIAlertController with Two Buttons and UITextField

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()
}

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    
    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)
}
}

[raw_html_snippet id=”cookbookpagecoursesheader”]

Unit Testing Swift Mobile App

Apply Test-Driven Development(TDD) process to iOS mobile app development in Swift Preview this video course.