ios - 委托(delegate)协议(protocol)的实现方法在哪里调用?

标签 ios swift uikit delegation

我是 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/

相关文章:

ios - IB_DESIGNABLE 绘制图像

iphone - 为什么 UITextField 的窗口为零?

objective-c - Undefined symbol for architecture i386 由 CACurrentMediaTime() 引起的编译错误

iOS:有选择地禁用 captureOutput 的处理:didOutputSampleBuffer:fromConnection:来自 AVFoundation 中的主线程

ios - println(currentWeatherDictionary) 函数不工作

Swift - 在基于闭包的配置中避免强引用循环

ios - 当 Accessory InputView 不存在键盘时,键盘将显示调用的通知

ios - 使用滑动手势时 TabController 消失

ios - 对象停止移动 - UIDynamics 和 Swift iOS

ios - viewWillTransitionToSize :withTransitionCoordinator: called when app goes into the background or inactive