我有以下代码。 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/