ios – 无法在关闭中找到成员

前端之家收集整理的这篇文章主要介绍了ios – 无法在关闭中找到成员前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有以下代码.提示是一个UIAlertController.
self.presentViewController(prompt,animated: true,completion: {
     prompt.textFields[0].becomeFirstResponder()
})

但它给了我这个错误:无法找到成员’becomeFirstResponder’.

然而,如果我把它放在它的工作正常:

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

当我添加如上所述的无用代码行时,为什么错误会消失?

解决方法@H_301_14@
根据关于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()
    }
})

原文链接:https://www.f2er.com/iOS/334012.html

猜你在找的iOS相关文章