Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift UIAlertController Getting Text Field Text

I need to get the text from the text fields in my alert view when the Input button is pressed.

func inputMsg() {

    var points = ""
    var outOf = ""

    var alertController = UIAlertController(title: "Input View", message: "Please Input Your Grade", preferredStyle: UIAlertControllerStyle.Alert)

    let actionCancle = UIAlertAction(title: "Cancle", style: UIAlertActionStyle.Cancel) { ACTION in

        println("Cacle")
    }
    let actionInput = UIAlertAction(title: "Input", style: UIAlertActionStyle.Default) { ACTION in

        println("Input")
        println(points)
        println(outOf)
    }

    alertController.addAction(actionCancle)
    alertController.addAction(actionInput)
    alertController.addTextFieldWithConfigurationHandler({(txtField: UITextField!) in
        txtField.placeholder = "I got"
        txtField.keyboardType = UIKeyboardType.NumberPad
        points = txtField.text
        })



    alertController.addTextFieldWithConfigurationHandler({(txtField: UITextField!) in
        txtField.placeholder = "Out Of"
        txtField.keyboardType = UIKeyboardType.NumberPad
        outOf = txtField.text
    })
    presentViewController(alertController, animated: true, completion: nil)
}
like image 408
Henry oscannlain-miller Avatar asked Oct 10 '14 18:10

Henry oscannlain-miller


2 Answers

As requested here is an implementation solution.

alertController.addAction(UIAlertAction(title: "Submit", style: UIAlertActionStyle.Default,handler: {
            (alert: UIAlertAction!) in
            if let textField = alertController.textFields?.first as? UITextField{
                println(textField.text)
            }
        }))

As stated above, the alertController has a property called textFields. You can conditionally unwrap that property to safely access a text field if you have added one. In this case since there is only one text field I just did the unwrap using the first property. Hope it helps.

like image 61
Unome Avatar answered Oct 01 '22 00:10

Unome


The UIAlertController has a textFields property. That's its text fields. Any of your handlers can examine it and thus can get the text from any of the text fields.

like image 27
matt Avatar answered Sep 30 '22 22:09

matt