gpt4 book ai didi

ios - Swift 无法通过委托(delegate)调用协议(protocol)方法

转载 作者:搜寻专家 更新时间:2023-11-01 05:57:14 25 4
gpt4 key购买 nike

我有两个类(class)。一个类名为 ViewController,另一个类名为 TabView

我的目标是从 ViewController 调用 TabView 类中的函数 changeTab()

不知何故,我遇到了麻烦,因为每次我的委托(delegate)都是 nil

这是我的 ViewController 代码:

protocol TabViewProtocol: class {
func changeTab()
}

class ViewController: NSViewController {
// delegate
weak var delegateCustom : TabViewProtocol?

override func viewDidLoad() {
print(delegateCustom) // outputs "nil"
}

buttonClickFunction() {
print(delegateCustom) // outputs "nil"
delegateCustom?.changeTab() // doesn't work
}
}

这是我的 TabView 代码:

class TabView: NSTabViewController, TabViewProtocol {

let myVC = ViewController()

override func viewDidLoad() {
super.viewDidLoad()
myVC.delegateCustom = self
}

func changeTab() {
print("test succeed")
}
}

有人可以解释我做错了什么吗? - 我是委托(delegate)和协议(protocol)的新手......

最佳答案

您错误地使用了委托(delegate)模式。很难说出您要为哪个 Controller 定义协议(protocol)以及要采用哪个 Controller - 但这是一种可能的方法。

// 1. Define your protocol in the same class file as delegate property.
protocol TabViewProtocol: class {
func changeTab()
}

// 2. Define your delegate property
class ViewController: NSViewController {
// delegate
weak var delegateCustom : TabViewProtocol?

override func viewDidLoad() {
// It should be nil as you have not set the delegate yet.
print(delegateCustom) // outputs "nil"
}

func buttonClickFunction() {
print(delegateCustom) // outputs "nil"
delegateCustom?.changeTab() // doesn't work
}
}

// 3. In the class that will use the protocol add it to the class definition statement

class TabView: NSTabViewController, TabViewProtocol {

let myVC = ViewController()

override func viewDidLoad() {
super.viewDidLoad()
myVC.delegateCustom = self

// Should output a value now
print(myVC.delegateCustom) // outputs "self"
}

func changeTab() {
print("test succeed")
}
}

关于ios - Swift 无法通过委托(delegate)调用协议(protocol)方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37244758/

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