Linus
Linus

Reputation: 4783

Accessing UIAlertControllers textField

I'm having trouble accessing an UIAlertController's textField from within a handler action, I think. I've googled the error but didn't get too much out of it. I'm using Swift with Xcode 6.0.1. Here's the error:

'[AnyObject]?' does not have a member named 'subscript'

@IBAction func addPressed(sender: UIBarButtonItem) {
    var alert = UIAlertController(title: "New Event", message: "Name of the event?", preferredStyle: .ActionSheet)
    alert.addTextFieldWithConfigurationHandler(){
        textField in
        textField.placeholder = "Christmas"
        textField.becomeFirstResponder()
    }
    alert.addAction(UIAlertAction(title: "Save", style: .Default, handler: {
        action in
        var text = alert.textFields[0].text // <-- cant access alert? The exclamation mark appears here
    }))

}

Using ((alert.textFields[0] as UITextField).text) gives me the exactly same error.

Upvotes: 3

Views: 1638

Answers (1)

Ben
Ben

Reputation: 3485

All you need to do, is to unwrap the array of UITextFields and then cast it to a UITextField because it's actually a array of AnyObject.

Here is what the code should look like:

var text = (alert.textFields![0] as UITextField).text

Upvotes: 5

Related Questions