swift - 委托(delegate)回传不起作用

标签 swift delegates

在我的主“viewcontroller A”中有以下内容作为segue。它是一个 PageViewController。

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
    if (segue.identifier == "postChoice") {
        let dvc = segue.destinationViewController as! UINavigationController
        let controller = dvc.popoverPresentationController
        if (controller != nil) {
            controller!.delegate = self
        }
    }
}

另外,在我的“Viewcontoller A”中,我在顶部有 PostChoiceDelegate 引用

我的segue链接到一个UINavigationController,它弹出到一个TableViewController。 “ View Controller B”

VCB

protocol PostChoiceDelegate: class {
    func postChoiceSelected(whatStyle: String)
}

//in the vc class
weak var delegate: PostChoiceDelegate? = nil

然后,我有一个以编程方式制作的导航项,其目标操作为“uploadPost”,并且在 VCB 中,我有一个返回 nil 委托(delegate)的函数。它不应该返回“hello”,所以我将其传递给 VCA 来更新 postChoiceSelected() 的 VCA 中的函数,将 label.text 更新为 Hello?

func uploadPost() {
    delegate?.postChoiceSelected("hello")
    print(delegate?.postChoiceSelected("hello"))
    dismissViewControllerAnimated(true, completion:nil)
}

我已经尝试过了!而不是?等,但没有任何作用?有意见吗?

最佳答案

也许您正在某处设置,但我在您发布的代码中没有看到它。

委托(delegate)字段是一个可选值,可能有值,也可能没有值。您没有将此委托(delegate)属性设置为任何内容,因此它为零,并且此行不会被执行:

delegate?.postChoiceSelected("hello")

因为委托(delegate)是nil

如何解决?只需将此属性设置为实现 PostChoiceDelegate

的对象实例

因此请确保以下行实际执行:

controller!.delegate = self

其中 delegate 表示对 PostChoiceDelegate 的弱引用,而不是其他任何内容,并且 self 实际上实现了 PostChoiceDelegate

更新:所以我会进行以下更改:

let controller = dvc.popoverPresentationController as! ViewControllerThatImplementsYourDelegate

否则,该委托(delegate)是 UIPopoverPresentationControllerDelegate 而不是 PostChoiceDelegate

关于swift - 委托(delegate)回传不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34010621/

相关文章:

ios - 如何在 XCTestCase 中输入 UITextView

ios - 在属性检查器或 Controller 代码中启用用户交互?

swift - Swift 3中如何处理FBSDKGraphRequest的响应数据

objective-c - 协议(protocol)方法的默认值是可选的还是必需的?

c# - 将委托(delegate)作为参数的方法?

swift - UITableView 或 StackView

swift - 如何将 GoogleAnalytics header 导入库框架?

swift - 委托(delegate)方法: "willSpeakRangeOfSpeechString" of AVSpeechSynthesizerDelegate gets not called

c# - 如何在 C# 中使用预定义的类委托(delegate)

ios - UISearchBar 在点击时消失