gpt4 book ai didi

ios - 嵌入式 View Controller (Swift 3)中永远不会调用 addObserver 选择器函数

转载 作者:搜寻专家 更新时间:2023-11-01 06:33:15 25 4
gpt4 key购买 nike

我的 Storyboard设置了一个主 ViewController 和一个 NavigationController,其中嵌入了一个辅助 ViewController。主要的 ViewControllerNavigationController 与按下按钮时触发的显示转场相连。所附照片显示了我的 Storyboard。

Picture of my storyboard

当按钮被点击时,LabelViewController 中的标签应该改变,show segue 应该触发并显示 NavigationViewController(使用 LabelViewController嵌入式)。后半部分有效,显示了 NavigationViewController,但标签的值永远不会改变。

要更改标签的值,我正在使用 NotificationCenteraddObserverpost。虽然还有其他方法,但我需要使用 NotificationCenter 来传递数据 (userData)。

代码

在第一个 ViewController 中,我在按下按钮时触发的 IBAction 中有一行代码。

NotificationCenter.default.post(name: NSNotification.Name(rawValue: "changeLabelValue"), object: nil, userInfo: ["labelValue": "Changed value"])

然后,在 LabelViewControllerviewDidLoad 中,我有另一行用于观察者的代码。

NotificationCenter.default.addObserver(self, selector: #selector(changeLabelValue(_:)), name: NSNotification.Name(rawValue: "changeLabelValue"), object: nil)

选择器函数 changeLabelValue 如下所示。

func changeLabelValue(_ notification: NSNotification) {
label.text = notification.userInfo?["value"] as? String
}

问题

如上所述,show segue 触发并且我看到了 NavigationViewController,但是 LabelViewController 中的选择器函数 (changeLabelValue) 从来没有被调用。

最佳答案

您的函数永远不会被调用,因为它仅在第二个 View Controller 的 viewDidLoad 中被拒绝接收函数调用。但是,当您在第一个 View Controller 中按下按钮时,您的第二个 View Controller 尚未加载。

要正确传递数据,需要使用prepareForSegue。所以在你的第一个 View Controller 中,你需要首先检查你的 segue 目的地是否是 UINavigationController 因为你的第二个 View Controller 嵌入在里面。如果是这样,请检查导航 Controller 的 topViewController 是否是您的 SecondViewController。如果两者都为真,则传递数据,它将在 SecondViewControllerviewDidLoad 部分可用。示例代码:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let destinationViewController = segue.destination as? UINavigationController {
if let secondViewControoler = destinationViewController.topViewController as? SecondViewController {
secondViewControoler.yourProperty = self.yourLabel.text
}
}
}

关于ios - 嵌入式 View Controller (Swift 3)中永远不会调用 addObserver 选择器函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44805640/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com