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

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

How to Make a Freaking iPhone App - iOS 10 and Swift 3
icon icon

iOS 10 & Swift 3: From Beginner to Paid Professional

The Complete iOS 10 Developer Course - Build 21 Apps

Swift 3 - Learn to Code with Apple's New Language
icon icon

Learn How to Build Mobile Apps for iOS with Swift, PHP and MySQL
icon icon

Follow me on one of your favourite social networks to learn about new video tutorials and code examples:

Twitter: @SwiftVideoBlog
Google Plus: https://plus.google.com/+SergeyKargopolov/posts
Facebook: Swift Developer Blog on Facebook