ios - 访问 UIAlertControllers 文本字段

标签 ios xcode swift uialertcontroller

我认为在处理程序操作中访问 UIAlertController 的 textField 时遇到问题。我用谷歌搜索了这个错误,但并没有从中得到太多。我在 Xcode 6.0.1 中使用 Swift。这是错误:

'[AnyObject]?'没有名为“下标”的成员

@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) 给我完全相同的错误。

最佳答案

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

代码应该是这样的:

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

关于ios - 访问 UIAlertControllers 文本字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26155433/

相关文章:

c++ - 线程本地存储和 iOS

ios - 在 swift 2.0 中构建自定义相机应用程序时出错

Swift/Xcode 奇怪的行为 : "Use of undeclared type" error shown in case of struct used before declaration

ios - 如何在 Swift 中显示 SDWebimage 背景颜色

xcode - 在 Xcode (Swift) 中查看 NSData 内容

ios - 从按钮操作调用时 UIActivityIndi​​catorView 不显示

ios - 为什么我的变量为零?

ios - 我如何读取 Apple 的崩溃日志

json - 有没有办法在 Swift 中仅从 JSON 部分创建对象?

swift - 更新到 Xcode 8.3 后 UIButton 不工作