Tom*_*adi 1 macos delegates protocols ios swift
我有两节课.一个类被命名ViewController,另一个类被命名TabView.
我的目标是changeTab()从ViewController 调用一个位于TabView类中的函数.
不知怎的,我遇到了麻烦,因为每次我的代表都是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
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的TabView代码:
class TabView: NSTabViewController, TabViewProtocol {
let myVC = ViewController()
override func viewDidLoad() {
super.viewDidLoad()
myVC.delegateCustom = self
}
func changeTab() {
print("test succeed")
}
}
Run Code Online (Sandbox Code Playgroud)
有人能解释一下我做错了什么吗? - 我是代表和协议的新手......
您错误地使用了委托模式.很难说你想要为哪个控制器定义协议以及你想采用哪个控制器 - 但这是一种可能的方法.
// 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")
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5111 次 |
| 最近记录: |