2016-05-15 10 views
-1

私は2つのクラスを持っています。 1つのクラスの名前はViewControllerで、もう1つのクラスの名前はTabViewです。Swiftはデリゲート経由でプロトコルメソッドを呼び出せません

私の目標は、ViewControllerからTabViewクラスの内側にあるchangeTab()という関数を呼び出すことです。

どういうわけか、私の代議員が毎回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") 
    } 
} 

誰かが私が間違っているのものを私に説明できますか? - 私はデリゲートとプロトコルに新しいです...

+2

を設定しました'ViewController()'を介して - 新しいコントローラは、おそらくアプリケーションの残りの部分とは関係がありません。新しいインスタンスを作成するのではなく、2つのインスタンス間に何らかの接続が必要です。一般的には、インターフェースビルダーを使用して簡単に実行できるはずです。 – luk2302

+0

私の答えを更新しました。これは私が前にそれを持っていた方法です...うまく動作しません – Anokrize

+0

そして、私はそれを使用していないので、interfacebuilder経由で動作していません。 @ luk2302 – Anokrize

答えて

5

あなたは間違ってデリゲートパターンを使用しています。どのコントローラにプロトコルを定義したいのか、どちらのコントローラを採用したいのかを知るのは難しいですが、ここでは可能な方法の1つです。

// 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の既存のインスタンスを取得する必要があなたは常に新しい `ViewController`を作成している

myVC.delegateCustom = self 
関連する問題