【发布时间】:2020-01-04 17:15:24
【问题描述】:
我是 swift 和 OOP 编程的新手,我正在尝试在使用 UIKit 时理解委托模式。我想我理解移交一些类职责的概念:有一个(例如)textField 类 UITextField 的实例,它在 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 协议的方法:
extension ViewController: UITextFieldDelegate {
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
return false
}
... // other methods
}
在阅读教程时,我想到类似这样的逻辑必须在 UIKit 中的某个地方实现:
let allowEditing = delegate?.textFieldShouldBeginEditing() ?? true
但是我找不到这行代码所在的地方。我是否理解正确,这段代码的位置是什么?我搜索了文档和类实现,但没有找到。
【问题讨论】:
标签: ios swift uikit delegation