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

在第一个控制器中,内部发送操作按钮添加了通知发布方法

 @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方法在视图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函数。
请帮助我在这段代码。

最佳答案

您确实有对第二个视图控制器的引用。完全没有理由使用Notification。如果只有一个接收者并且对象相关,则不要使用通知。

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

忘记通知。而是在第二个视图控制器中创建属性,在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)

}


第二视图控制器

var message = ""

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

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

10-12 01:43
查看更多