Nathan Tsai
Nathan Tsai

Reputation: 21

Programmatically grab a changing textField in an UIAlertController

Generally, to grab the text of a UITextField every time it is changed, you just drag an IBOutlet from the Storyboard file, and select the "editing has changed" option.

However, I want to grab the text of a UITextField in a UIAlertController, so the text field is created programmatically, not via storyboard.

How do I programmatically create a function that runs every time a textfield (in the Alert window) has changed?

What I need:

func textHasChanged(textField: TextField) {
    print(textField.text)
}

If input is "cat" Needed Output needs to be:

"c"

"ca"

"cat"

How would I achieve this?

Note: I've tried doing the .addtarget method:

textField.addTarget(self, action: Selector(self.textFieldDidChange(_:)), for: UIControlEvents.editingChanged)

with this function in the same file:

func textFieldDidChange(txtField: UITextField)

But I keep getting this error: Value of type "name of my viewcontroller" has no member "textFieldDidChange"

I've looked up this question but most give me outdated answers. Thanks!

Upvotes: 1

Views: 407

Answers (1)

Code Different
Code Different

Reputation: 93161

Try this:

@IBAction func displayAlert(_ sender : AnyObject) {
    let alertController = UIAlertController(title: "Enter some text", message: "Please enter some text in the field below", preferredStyle: .alert)
    alertController.addTextField()
    alertController.addAction(UIAlertAction(title: "OK", style: .default) { action in
        print("User pressed OK")
    })
    alertController.addAction(UIAlertAction(title: "Cancel", style: .cancel) { action in
        print("User pressed Cancel")
    })


    if let textField = alertController.textFields?.first {
        textField.addTarget(self, action: #selector(ViewController.textHasChanged), for: .editingChanged)
    }
    self.present(alertController, animated: true)
}

Upvotes: 2

Related Questions