gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 01:06:54 24 4
gpt4 key购买 nike

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com