Get input value from TextField in iOS alert in Swift

swift get input from text field
uialertcontroller with textview swift 4
uialertcontroller get textfield value
swiftui alert with textfield
trigger alert swift
how to add textfield in swift
text field swift 5
dismiss alert swift

I'm trying to make an alert message with input, and then get the value from the input. I've found many good tutorials how to make the input text field. but I can't get the value from the alert.

Updated for Swift 3 and above:

//1. Create the alert controller.
let alert = UIAlertController(title: "Some Title", message: "Enter a text", preferredStyle: .alert)

//2. Add the text field. You can configure it however you need.
alert.addTextField { (textField) in
    textField.text = "Some default text"
}

// 3. Grab the value from the text field, and print it when the user clicks OK.
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { [weak alert] (_) in
    let textField = alert.textFields![0] // Force unwrapping because we know it exists.
    print("Text field: \(textField.text)")
}))

// 4. Present the alert.
self.present(alert, animated: true, completion: nil)

Swift 2.x

Assuming you want an action alert on iOS:

//1. Create the alert controller.            
var alert = UIAlertController(title: "Some Title", message: "Enter a text", preferredStyle: .Alert)

//2. Add the text field. You can configure it however you need.
alert.addTextFieldWithConfigurationHandler({ (textField) -> Void in
    textField.text = "Some default text."
})

//3. Grab the value from the text field, and print it when the user clicks OK. 
alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: { [weak alert] (action) -> Void in
    let textField = alert.textFields![0] as UITextField
    println("Text field: \(textField.text)")
}))

// 4. Present the alert.
self.presentViewController(alert, animated: true, completion: nil)

How to add TextField to UIAlertController in Swift, Swift 5.1. alert.addTextField { (textField) in textField.placeholder = "Enter First Name" }. Use this code, I am running this code in my app successfully. @IBAction   You can configure it however you need. alert.addTextField { (textField) in textField.text = "Some default text" } // 3. Grab the value from the text field, and print it when the user clicks OK. alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { [weak alert] (_) in let textField = alert.textFields![0] //

Swift 3/4

You can use the below extension for your convenience.

Usage inside a ViewController:

showInputDialog(title: "Add number",
                subtitle: "Please enter the new number below.",
                actionTitle: "Add",
                cancelTitle: "Cancel",
                inputPlaceholder: "New number",
                inputKeyboardType: .numberPad)
{ (input:String?) in
    print("The new number is \(input ?? "")")
}

The extension code:

extension UIViewController {
    func showInputDialog(title:String? = nil,
                         subtitle:String? = nil,
                         actionTitle:String? = "Add",
                         cancelTitle:String? = "Cancel",
                         inputPlaceholder:String? = nil,
                         inputKeyboardType:UIKeyboardType = UIKeyboardType.default,
                         cancelHandler: ((UIAlertAction) -> Swift.Void)? = nil,
                         actionHandler: ((_ text: String?) -> Void)? = nil) {

        let alert = UIAlertController(title: title, message: subtitle, preferredStyle: .alert)
        alert.addTextField { (textField:UITextField) in
            textField.placeholder = inputPlaceholder
            textField.keyboardType = inputKeyboardType
        }
        alert.addAction(UIAlertAction(title: actionTitle, style: .default, handler: { (action:UIAlertAction) in
            guard let textField =  alert.textFields?.first else {
                actionHandler?(nil)
                return
            }
            actionHandler?(textField.text)
        }))
        alert.addAction(UIAlertAction(title: cancelTitle, style: .cancel, handler: cancelHandler))

        self.present(alert, animated: true, completion: nil)
    }
}

How to add a UITextField to a UIAlertController, Find a Job The UIAlertController class from iOS 8.0 lets you add as many text fields as you need, and you can read the value of those text fields when the user taps a button. below creates an alert controller with one button and a text field. When the button is tapped, the text of the text field is pulled out,  This question has been asked before, in:Get input value from TextField in iOS alert in Swift. However, does somebody have the code in the Objective-C language? Thanks in advance! What I've gotten

In Swift5 ans Xcode 10

Add two textfields with Save and Cancel actions and read TextFields text data

func alertWithTF() {
    //Step : 1
    let alert = UIAlertController(title: "Great Title", message: "Please input something", preferredStyle: UIAlertController.Style.alert )
    //Step : 2
    let save = UIAlertAction(title: "Save", style: .default) { (alertAction) in
        let textField = alert.textFields![0] as UITextField
        let textField2 = alert.textFields![1] as UITextField
        if textField.text != "" {
            //Read TextFields text data
            print(textField.text!)
            print("TF 1 : \(textField.text!)")
        } else {
            print("TF 1 is Empty...")
        }

        if textField2.text != "" {
            print(textField2.text!)
            print("TF 2 : \(textField2.text!)")
        } else {
            print("TF 2 is Empty...")
        }
    }

    //Step : 3
    //For first TF
    alert.addTextField { (textField) in
        textField.placeholder = "Enter your first name"
        textField.textColor = .red
    }
    //For second TF
    alert.addTextField { (textField) in
        textField.placeholder = "Enter your last name"
        textField.textColor = .blue
    }

    //Step : 4
    alert.addAction(save)
    //Cancel action
    let cancel = UIAlertAction(title: "Cancel", style: .default) { (alertAction) in }
    alert.addAction(cancel)
    //OR single line action
    //alert.addAction(UIAlertAction(title: "Cancel", style: .default) { (alertAction) in })

    self.present(alert, animated:true, completion: nil)

}

For more explanation https://medium.com/@chan.henryk/alert-controller-with-text-field-in-swift-3-bda7ac06026c

[solved] - xcode, addTextField { (textField) in textField.text = "Some default text" } // 3. Grab the value from the text field, and print it when the user clicks OK. alert. Save the project and run in either the simulator or your device and try it out. Click the button on the view and the alert should appear waiting for some input. Enter some text and touch / click Submit. You should now see the text you entered on the view displayed in the label.

Alert Controller with Text Field in Swift 3 - Henry Chan, Let's get started! Step One: let alert = UIAlertController(title: "Great Title", message: "Please input something", preferredStyle:  alert.addTextField { (textField) in textField.placeholder = "User" } alert.addTextField { (textFieldPass) in textFieldPass.placeholder = "Password" textFieldPass.isSecureTextEntry = true } // 3. Grab the value from the text field, and print it when the user clicks OK.

Get input value from TextField in iOS alert in Swift, Get input value from TextField in iOS alert in Swift - ios. "Some default text" } // 3 . Grab the value from the text field, and print it when the user clicks OK. alert. Tap on the check amount text field, then enter some text – it doesn’t need to be a number; anything will do. What you’ll see is that as you type the text view in the second section automatically and immediately reflects your actions. This synchronization happens because: Our text field has a two-way binding to the checkAmount property.

Editable Text Field inside Alert Controller iOS Tutorial, Using the UIAlertController class it is not only possible to show alerts, but also get text input using Text Fields. In this tutorial a username and  In iOS apps sometimes we need to restrict our text field to take only numbers as an input, this can be done in several ways, let’s see some of them. Method 1: Changing the Text Field Type from storyboard. Select the text field that you want to restrict to numeric input. Go to its attribute inspector.

Comments
  • A action alert on iOS?
  • @AndyIbanez Yes, didn't mention that!
  • Not a problem. Please remember to mark this as Accepted if it helped you. Thanks!
  • Hi @AndyIbanez I'm trying to implement your code on my app, however its stating the error "Use of undeclared identifier var" I'm new to Xcode so apologies if this is a basic error on my behalf
  • @Sjharrison My code is for Swift. The only reason I can think of that would cause you troubles with the var keyword is if you were writing in Objective-C.
  • Can anyone explain why the [weak alert]? I'm looking at Swift 3.
  • For Swift 3 alert in step 3. is optional, needed "?" let textField = alert?.textFields![0] // Force unwrapping because we know it exists. print("Text field: \(textField?.text)")
  • just note that if you are going to present "Add" action make sure the style if "default" not "destructive" -- alert.addAction(UIAlertAction(title: actionTitle, style: .default ...