简体   繁体   English

NotificationCenter Selector方法未在Swift中调用

[英]NotificationCenter Selector method is not calling in Swift

I am trying to send first viewcontroller textfield data into second viewcontroller label. 我正在尝试将第一个viewcontroller文本字段数据发送到第二个viewcontroller标签中。

In first controller, Inside send action button adding notification post method 在第一个控制器中,“内部发送操作”按钮添加了通知发布方法

 @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])
   }

And second viewcontroller addobserver method inside view didload 第二个viewcontroller addobserver方法在视图didload中

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

Selector function : 选择器功能:

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

When keeping break points for add observer it observers but it does not calling showMsg function. 当为添加观察者保留断点时,它是观察者,但不调用showMsg函数。 Please help me in this code. 请帮助我在这段代码。

You do have the reference to the second view controller. 确实有对第二个视图控制器的引用。 There is no reason at all to use Notification . 根本没有理由使用Notification Don't use notifications if there is only one receiver and the objects are related. 如果只有一个接收者并且对象相关,则不要使用通知。

The code doesn't work because the view is not loaded yet when the notification is sent. 该代码不起作用,因为发送通知时尚未加载视图。

Forget the notification. 忘记通知。 Instead create a property in the second view controller, assign the value in sendtBtn and show the message in viewDidLoad 而是在第二个视图控制器中创建属性,在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)

}

Second view controller 第二视图控制器

var message = ""

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM