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


Learn iOS Development with these Video Courses

The Complete iOS 11 & Swift Developer Course - Build 20 Apps

Use Xcode 9 & Swift 4 to make real apps like Uber and Instagram, with CoreML & ARKit. Includes AWS Credit and much more. Preview this video course. icon

How to Make a Freaking iPhone App - iOS 11 and Swift 4

iPhone App Development from scratch. Learn how to make iOS apps using Xcode 9. The Basics Include Pokemon Go & Snapchat. Learn to build iOS Apps with Xcode 9 and Swift 4. How to Make a Freaking iPhone App - iOS 11 and Swift 4 icon

iOS 11 and Xcode 9 - Complete Swift 4 & Objective-C Course

A Complete iOS 11 and Xcode 9 Course with Swift 4 & Objective-C. Preview this video course. iOS 11 and Xcode 9 - Complete Swift 4 & Objective-C Course icon