我有两堂课。一个类名为ViewController,另一个类名为TabView。
我的目标是从changeTab()调用TabView类中的函数ViewController。
不知怎么的,我在这方面有困难,因为每次我的代表都是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")
}
}有人能解释我做错了什么吗?-我对代表和协议不熟悉.
发布于 2016-05-16 01:00:33
您错误地使用了委托模式。很难说您想要为哪个控制器定义协议,以及您想采用哪个控制器--但这里有一种可能的方法。
// 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")
}
}发布于 2016-05-16 06:10:11
您正在此行中创建一个新实例:
let myVC = ViewController()您应该获得ViewController.then集的现有实例。
myVC.delegateCustom = selfhttps://stackoverflow.com/questions/37244758
复制相似问题