访问UIAlertControllers textField

时间:2014-10-02 06:24:35

标签: ios xcode swift uialertcontroller

我想在处理程序操作中访问UIAlertController的textField时遇到了麻烦。我已经用Google搜索了错误,但没有从中得到太多。我正在使用Swift和Xcode 6.0.1。这是错误:

'[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
    }))

}

使用((alert.textFields[0] as UITextField).text)给出了完全相同的错误。

1 个答案:

答案 0 :(得分:5)

您需要做的就是打开UITextFields数组,然后将其转换为UITextField,因为它实际上是AnyObject数组。

以下是代码的样子:

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