我有以下代码.提示是一个UIAlertController.
self.presentViewController(prompt,animated: true,completion: { prompt.textFields[0].becomeFirstResponder() })
但它给了我这个错误:无法找到成员’becomeFirstResponder’.
然而,如果我把它放在它的工作正常:
self.presentViewController(prompt,completion: { let foo = 0 prompt.textFields[0].becomeFirstResponder() })
解决方法
根据关于If语句和强制解包的Swift编程语言一书的部分,
“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不必具有textField,因为textFields数组是可选的,你必须先打开它才能调用数组内部对象的函数,所以看起来应该是这样的:
self.presentViewController(prompt,completion: { if let textFields = prompt.textFields { textFields[0].becomeFirstResponder() } })