【问题标题】:Swift can't call protocol method via delegateSwift 不能通过委托调用协议方法
【发布时间】:2016-05-15 23:30:55
【问题描述】:

我有两节课。一类名为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")
    }
}

谁能解释我做错了什么? - 我是代表和协议的新手...

【问题讨论】:

  • 您总是通过ViewController() 创建一个新的ViewController - 这个新控制器可能与应用程序的其余部分无关。您必须在两个实例之间建立某种联系——而不是创建新实例。一般来说,使用界面生成器应该很容易做到这一点。
  • 更新了我的答案。这就是我以前的方式......效果不佳
  • 它不能通过 interfacebuilder 工作,因为我没有使用它。 @luk2302
  • 该代码不会改变任何事情 - 您仍然为 TabView 创建一个新的 ViewController 实例。您已链接两个 现有 实例,而不是创建新实例。
  • 你告诉我 - 我不知道你的项目设置。我告诉你做什么你需要做。不幸的是,我无法告诉您如何 这样做,因为这是非常笼统的建议,而且本身就很不言自明。

标签: ios swift macos delegates protocols


【解决方案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")
    }
}

【讨论】:

    【解决方案2】:

    您正在此行中创建一个新实例:

    let myVC = ViewController()
    

    你应该得到你的 ViewController 的现有实例。然后设置

    myVC.delegateCustom = self
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-01-13
      • 2018-10-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多