Swift - 委托不从其他 class 调用方法

Swift - Delegate not calling method from other class

我正在尝试在按下按钮时更改另一个视图控制器中的标签文本。以下是我设置委托的方式:

import UIKit

下的FirstViewController中
@objc protocol MyDelegate{
    optional func makeScore()
}

class FirstViewController: UIViewController下的FirstViewController

var delegate:MyDelegate?

在按下按钮时在 FirstViewController 中

delegate?.makeScore!()

在SecondViewController中(makeScore()所在位置)

class SecondViewController: UIViewController, MyDelegate

SecondViewController中的makeScore()方法

func makeScore() {
    println("worked")
}

按下按钮时没有记录任何内容。我很确定我正确地设置了代表和协议。你看到有什么遗漏了吗?

注意:FirstViewControllerSecondViewController 没有通过 segues 连接。他们都在 scrollView.

我现在可以看到您使用以下行以编程方式添加了第二个视图控制器:

let vc6 = storyboard.instantiateViewControllerWithIdentifier("Second") as! SecondViewController
self.addChildViewController(vc6)
self.scrollView.addSubview(vc6.view)

只需添加一行,这样就可以写成这样:

let vc6 = storyboard.instantiateViewControllerWithIdentifier("Second") as! SecondViewController
self.delegate = vc6
self.addChildViewController(vc6)
self.scrollView.addSubview(vc6.view)

编辑: 在侧面节点上,我确信委托实际上是您尝试做的事情的最佳方法。您最好只对 SecondViewController 进行全局引用,然后调用 self.vc6.makeScore()。委托通常用于回调未包含在视图控制器中的对象