gpt4 book ai didi

ios - NotificationCenter Selector 方法未在 Swift 中调用

转载 作者:行者123 更新时间:2023-11-28 23:46:51 26 4
gpt4 key购买 nike

我正在尝试将第一个 View Controller 文本字段数据发送到第二个 View Controller 标签中。

在第一个 Controller 中,在发送操作按钮中添加通知发布方法

 @IBAction func sendtBtn(_ sender: Any) {
let secVc = storyboard?.instantiateViewController(withIdentifier: "SecondViewController") as! SecondViewController
self.navigationController?.pushViewController(secVc, animated: true)

NotificationCenter.default.post(name: Notification.Name( "notificationName"), object: nil, userInfo: ["text": firstTextField.text])
}

第二个 viewcontroller addobserver 方法在 View didload 中

   NotificationCenter.default.addObserver(self, selector: #selector(self.showMsg(_:)), name: Notification.Name( "notificationName"), object: nil)

选择器函数:

func showMsg(_ notification: Notification){
print("helloooo")
var vcData = notification.userInfo?["text"]
firstLabel.text = vcData as! String
}

当为添加观察者保留断点时,它观察者但不调用 showMsg 函数。请帮助我编写这段代码。

最佳答案

确实拥有对第二个 View Controller 的引用。 根本没有理由使用通知。如果只有一个接收者并且对象相关,请勿使用通知。

该代码不起作用,因为发送通知时 View 尚未加载。

忘记通知。相反,在第二个 View Controller 中创建一个属性,在 sendtBtn 中分配值并在 viewDidLoad

中显示消息
@IBAction func sendtBtn(_ sender: Any) {
let secVc = storyboard?.instantiateViewController(withIdentifier: "SecondViewController") as! SecondViewController
secVc.message = firstTextField.text
self.navigationController?.pushViewController(secVc, animated: true)

}

第二个 View Controller

var message = ""

func viewDidLoad() {
super.viewDidLoad()
firstLabel.text = message
}

关于ios - NotificationCenter Selector 方法未在 Swift 中调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52552455/

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