gpt4 book ai didi

swift - 非自委托(delegate)不被调用

转载 作者:行者123 更新时间:2023-11-28 06:37:25 24 4
gpt4 key购买 nike

考虑以下代码。一切都由书完成,除了委托(delegate)被分配了一个除 self 之外的其他类的实例。然而这段代码失败了——永远不会调用委托(delegate)。这是为什么?

class My: UITextField {
...
init(...) {
delegate = MyDelegate()
}
}

public class MyDelegate: NSObject, UITextFieldDelegate {
public func textFieldDidBeginEditing(_ textField: UITextField) {
print("MyDelegate was called")
}
}

最佳答案

如果您的委托(delegate)属性是使用 weak var 定义的,则不会保留 MyDelegate 实例。如果没有强引用,它将很快被释放并且不再存在以接收调用。

您的示例代码偏离了典型的委托(delegate)模式:

Delegation and the Cocoa Frameworks

The delegating object is typically a framework object, and the delegate is typically a custom controller object.

文本字段的 View Controller 通常会将自己指定为文本字段的委托(delegate):

class MyViewController: UITextFieldDelegate {

...

func viewDidLoad() {
myTextField.delegate = self
}

func textFieldDidBeginEditing(_ textField: UITextField) {
print("textFieldDidBeginEditing")
}
}

关于swift - 非自委托(delegate)不被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38819178/

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