Accessing UIAlertControllers textField

本秂侑毒 提交于 2019-12-01 05:40:39

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/26155433/accessing-uialertcontrollers-textfield

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!