NotificationCenter 选择器方法未在 Swift 中调用
NotificationCenter Selector method is not calling in Swift
我正在尝试将第一个 viewcontroller 文本字段数据发送到第二个 viewcontroller 标签。
在第一个控制器中,Inside send action button adding notification post方法
@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
}
我正在尝试将第一个 viewcontroller 文本字段数据发送到第二个 viewcontroller 标签。
在第一个控制器中,Inside send action button adding notification post方法
@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
}