簡體   English   中英

Swift無法通過委托調用協議方法

[英]Swift can't call protocol method via delegate

我有兩節課。 一個類名為ViewController ,另一個類名為TabView

我的目標是從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")
    }
}

有人可以解釋我在做什么嗎? -我是代表和協議的新手...

您錯誤地使用了委托模式。 很難說出要為哪個控制器定義協議以及要采用哪個協議-但這是一種可能的方法。

// 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM