ios - 在关闭中找不到成员

标签 ios swift

我有以下代码。 prompt 是一个 UIAlertController

self.presentViewController(prompt, animated: true, completion: {
     prompt.textFields[0].becomeFirstResponder()
})

但它给了我这个错误:Could not find member 'becomeFirstResponder'

然而,如果我把它放进去,它就可以正常工作:

self.presentViewController(prompt, animated: true, completion: {
     let foo = 0
     prompt.textFields[0].becomeFirstResponder()
})

为什么当我添加一行无用的代码(如上面)时错误消失了?

最佳答案

根据 Swift 编程语言书籍关于 If 语句和强制展开的部分,

“You can use an if statement to find out whether an optional contains a value. If an optional does have a value, it evaluates to true; if it has no value at all, it evaluates to false. Once you’re sure that the optional does contain a value, you can access its underlying value”

UIAlertController 不必有 textFields,所以因为 textFields 数组是可选的,你必须先打开它才能调用数组内对象的函数,所以它应该看起来像像这样:

self.presentViewController(prompt, animated: true, completion: {
    if let textFields = prompt.textFields {
       textFields[0].becomeFirstResponder()
    }
})

关于ios - 在关闭中找不到成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24047333/

相关文章:

javascript - 触摸设备上的 Twitter 提前输入 - 现在有什么交易?

ios - Swift:比较字典键

ios - UICollectionView:使用 UIStackView 的动态单元格高度

ios - 如何在适用于 iOS 的 Google Material Design 上禁用水平滚动到选项卡

iOS 命令行构建 : How to create xcode archive from command line?

ios - 无需编译即可使用的扩展

ios - 使用 CGContextRef 设置上下文

ios - 在 for 循环中安排本地通知

swift - 完成处理程序没有按预期的 Swift 被调用

ios - Swift CollectionView 排序困惑