2016-05-15 129 views
-1

我有兩個類。一個班級名爲ViewController,另一個班級名爲TabViewSwift不能通過委託調用協議方法

我的目標是調用函數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") 
    } 
} 

有人可以解釋我什麼,我做錯了什麼? - 我是代表和協議的新成員...

+2

你總是創建一個新的'ViewController'通過'ViewController()' - 新的控制器可能與應用程序的其餘部分無關。你必須在兩個實例之間有一些連接,而不是創建新的實例。一般來說,使用界面構建器應該很容易實現。 – luk2302

+0

更新了我的答案。這是我以前的做法......不能很好地工作 – Anokrize

+0

而且它不是通過interfacebuilder工作,因爲我沒有使用它。 @ luk2302 – Anokrize

回答

5

您正在錯誤地使用委託模式。很難告訴你想要爲哪個控制器定義協議,以及要採用哪個控制器 - 但這裏有一種可能的方法。

// 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") 
    } 
} 
0

你在這一行建立一個新的實例:

let myVC = ViewController() 

你應該得到現有的ViewController.then的實例設置

myVC.delegateCustom = self