我是 swift 和 OOP 编程的新手,我试图在使用 UIKit 时理解委托(delegate)模式。我想我理解移交一些类职责的概念:UITextField
类有一个(例如)textField
实例,它在 ViewController< 中实现了一些逻辑
:
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 协议(protocol)的方法:
extension ViewController: UITextFieldDelegate {
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
return false
}
... // other methods
}
在阅读教程时,我想到类似的逻辑必须在 UIKit 中的某个位置实现:
let allowEditing = delegate?.textFieldShouldBeginEditing() ?? true
但是我找不到这行代码所在的地方。我理解正确吗?这段代码在哪里?我搜索了文档和类实现,但没有找到。
最佳答案
你说得对!
您要查找的代码位于 UIKit
的私有(private)部分内,您看不到它。所有实现都是私有(private)的。
请注意,此方法是 Objective-C 可选方法,因此将像这样调用它(如果是 Swift 代码):
guard delegation?.textFieldShouldBeginEditing?() ?? true else { return }
becomeFirstResponder()
看到()
之前的吗?
?
请注意,UIKit
是用 Objective-C 编写的,如果您想深入研究这两种语言,则应该考虑它们之间的差异。
关于ios - 委托(delegate)协议(protocol)的实现方法在哪里调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57743866/