【问题标题】:Swift - Delegate not calling method from other classSwift - 委托不从其他类调用方法
【发布时间】:2015-04-22 18:03:29
【问题描述】:

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

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

【问题讨论】:

  • 你在哪里分配delegate属性?
  • 就在我的@IBOutletsviewDidLoad 覆盖之间。
  • 这声明了委托,但您需要在某处为其分配一个 SecondViewController 实例以使该通信正常工作。
  • 我对 viewController 的流程感到困惑。您是否尝试将SecondViewController 推到FirstViewController 之上,并将SecondViewControler 的代表分配给FirstViewController?如果是这样,则需要对您的委托声明进行一些更改
  • FirstViewController 是一个带有 ScrollView 的 ViewController。 SecondViewController 是一个 ViewController,它被细分到该 ScrollView 中。

标签: ios xcode swift delegates protocols


【解决方案1】:

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

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()。委托通常用于回调未包含在视图控制器中的对象

【讨论】:

  • 我以编程方式完成了它,但它不允许我设置委托。这是我使用的代码:let vc6 = storyboard.instantiateViewControllerWithIdentifier("Second") as! SecondViewController
  • 如何将第二个视图控制器添加到第一个视图控制器的滚动视图中?是通过情节提要还是以编程方式进行?
  • 我正在以编程方式进行:self.addChildViewController(vc6)self.scrollView.addSubview(vc6.view)
  • 哦,我看错了你的代码,你实际上需要做self.delegate = vc6
  • 现在可以使用了!几个小时的查找,这就是我必须添加的全部内容
猜你喜欢
  • 2014-12-10
  • 2021-02-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多