我对 swift 还很陌生,我无法理解以下情况。我正在尝试使用几个 UITextFieldDelegate 函数扩展 UIViewController 类...
class ViewController: UIViewController{
@IBOutlet weak var textField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
textField.delegate = self
在另一个文件中,如果我在参数未包装的情况下定义函数,则不会调用该函数...
extension UIViewController: UITextFieldDelegate{
internal func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
print("Text Field Should Begin Editing called")
return true
}
但是如果我解开参数,它就可以工作。
internal func textFieldShouldBeginEditing(_ textField: UITextField!) -> Bool
你能帮我理解为什么吗? 谢谢
swift 4.2
最佳答案
由于 Objective-C 不保证对象非零,因此 Swift 在导入的 Objective-C API 中使参数类型和返回类型中的所有类都是可选的。在使用 Objective-C 对象之前,您应该检查以确保它没有丢失。
如果您使用 _ textField: UITextField
参数可以为 null,因此委托(delegate)不会调用该方法,因为它在方法签名中查找非空值,即 internal func textFieldShouldBeginEditing (_ textField: UITextField!) -> Bool
关于ios - swift UITextFieldDelegate 扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55087780/