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

我有以下代码.提示一个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()
    }
})

相关文章

UITabBarController 是 iOS 中用于管理和显示选项卡界面的一...
UITableView的重用机制避免了频繁创建和销毁单元格的开销,使...
Objective-C中,类的实例变量(instance variables)和属性(...
从内存管理的角度来看,block可以作为方法的传入参数是因为b...
WKWebView 是 iOS 开发中用于显示网页内容的组件,它是在 iO...
OC中常用的多线程编程技术: 1. NSThread NSThread是Objecti...