简体   繁体   English

Swift无法通过委托调用协议方法

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

I have two classes. 我有两节课。 One class is named ViewController and the other class is named TabView . 一个类名为ViewController ,另一个类名为TabView

My goal is to call a function changeTab() which is inside the TabView class from the ViewController. 我的目标是从ViewController调用TabView类内部的函数changeTab()

Somehow I am having trouble with it because everytime my delegate is nil . 我莫名其妙地遇到了麻烦,因为每次我的代表都nil

Here is my code for ViewController: 这是我的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
    }
}

Here is my code for TabView: 这是我的TabView代码:

class TabView: NSTabViewController, TabViewProtocol {

    let myVC = ViewController()

    override func viewDidLoad() {
        super.viewDidLoad()
        myVC.delegateCustom = self
    }

    func changeTab() {
        print("test succeed")
    }
}

Can someone explain me what I am doing wrong? 有人可以解释我在做什么吗? - I am new to delegates and protocols... -我是代表和协议的新手...

You are using the delegate pattern wrongly. 您错误地使用了委托模式。 It is hard to tell which controller you want to define the protocol for and which one you want to adopt it - but here is one possible way. 很难说出要为哪个控制器定义协议以及要采用哪个协议-但这是一种可能的方法。

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

you are creating a new instance in this line: 您正在此行中创建一个新实例:

let myVC = ViewController()

you should get existing instance of your ViewController.then set 您应该获取ViewController.then的现有实例

myVC.delegateCustom = self

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM