Swift不能通过委托调用协议方法
问题描述:
我有两个类。一个班级名为ViewController
,另一个班级名为TabView
。Swift不能通过委托调用协议方法
我的目标是调用函数changeTab()
,该函数位于ViewController的TabView类中。
不知何故,我有麻烦,因为每次我的代表是nil
。
这里是我的视图控制器代码:
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")
}
}
有人可以解释我什么,我做错了什么? - 我是代表和协议的新成员...
答
您正在错误地使用委托模式。很难告诉你想要为哪个控制器定义协议,以及要采用哪个控制器 - 但这里有一种可能的方法。
// 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")
}
}
答
你在这一行建立一个新的实例:
let myVC = ViewController()
你应该得到现有的ViewController.then的实例设置
myVC.delegateCustom = self
你总是创建一个新的'ViewController'通过'ViewController()' - 新的控制器可能与应用程序的其余部分无关。你必须在两个实例之间有一些连接,而不是创建新的实例。一般来说,使用界面构建器应该很容易实现。 – luk2302
更新了我的答案。这是我以前的做法......不能很好地工作 – Anokrize
而且它不是通过interfacebuilder工作,因为我没有使用它。 @ luk2302 – Anokrize