委托协议的实现方法在哪里调用?
Where are implemented methods of delegate protocols called?
我是 swift 和 OOP 编程的新手,我正在尝试了解使用 UIKit 时的委托模式。我想我理解移交一些 class 职责的概念:class UITextField
有一个(例如)textField
实例,它在 [=15] 中实现了一些逻辑=]:
class ViewController: UIViewController {
let textField = UITextField(frame: CGRect(...))
override func viewDidLoad() {
textField.contentVerticalAlignment = .center
textField.borderStyle = .roundedRect
textField.placeholder = "Help me to figure it out"
textField.delegate = self // set the controller as a delegate
self.view.addSubview(textField)
}
}
还有一个 ViewController 的扩展,它实现了 UITextFieldDelegate 协议的方法:
extension ViewController: UITextFieldDelegate {
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
return false
}
... // other methods
}
在阅读教程时,我想到类似这样的逻辑必须在 UIKit 的某处实现:
let allowEditing = delegate?.textFieldShouldBeginEditing() ?? true
但是我找不到这行代码所在的地方。我是否理解正确,这段代码的位置是什么?我搜索了文档和 classes 实现,但没有找到它。
你没看错!
您要查找的代码在 UIKit
的私有部分中,您看不到它。所有实现都是私有的。
请注意,此方法是 objective-c 可选方法,因此将像这样调用(如果它是 Swift 代码):
guard delegation?.textFieldShouldBeginEditing?() ?? true else { return }
becomeFirstResponder()
在 ()
之前看到 ?
?
请注意 UIKit
是用 objective-c 编写的,如果您想深入研究这两种语言,您应该考虑它们之间的差异。
我是 swift 和 OOP 编程的新手,我正在尝试了解使用 UIKit 时的委托模式。我想我理解移交一些 class 职责的概念:class UITextField
有一个(例如)textField
实例,它在 [=15] 中实现了一些逻辑=]:
class ViewController: UIViewController {
let textField = UITextField(frame: CGRect(...))
override func viewDidLoad() {
textField.contentVerticalAlignment = .center
textField.borderStyle = .roundedRect
textField.placeholder = "Help me to figure it out"
textField.delegate = self // set the controller as a delegate
self.view.addSubview(textField)
}
}
还有一个 ViewController 的扩展,它实现了 UITextFieldDelegate 协议的方法:
extension ViewController: UITextFieldDelegate {
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
return false
}
... // other methods
}
在阅读教程时,我想到类似这样的逻辑必须在 UIKit 的某处实现:
let allowEditing = delegate?.textFieldShouldBeginEditing() ?? true
但是我找不到这行代码所在的地方。我是否理解正确,这段代码的位置是什么?我搜索了文档和 classes 实现,但没有找到它。
你没看错!
您要查找的代码在 UIKit
的私有部分中,您看不到它。所有实现都是私有的。
请注意,此方法是 objective-c 可选方法,因此将像这样调用(如果它是 Swift 代码):
guard delegation?.textFieldShouldBeginEditing?() ?? true else { return }
becomeFirstResponder()
在 ()
之前看到 ?
?
请注意 UIKit
是用 objective-c 编写的,如果您想深入研究这两种语言,您应该考虑它们之间的差异。