我有两个ViewController1和ViewController2。
我正在将通知从ViewController1发布到ViewController2,但在第一次发布时,NotificationCenter第一次不工作。
当我从ViewController2返回ViewController1,然后再次尝试移动ViewController2,则时间通知中心正在工作,
//视图控制器1.swift
import UIKit
class ViewController1: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
//Move to next VC
@IBAction func nextButtonClicked(_ sender: Any) {
NotificationCenter.default.post(name: Notification.Name("callMethodPrint1FromVC2"), object: nil)
let storyBoard = UIStoryboard(name: "Main", bundle: nil)
let vc2 = storyBoard.instantiateViewController(withIdentifier: "ViewController2Id") as? ViewController2
navigationController?.pushViewController(vc2!, animated: true)
}
}
//视图控制器2.swift
import UIKit
class ViewController2: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func viewWillAppear(_ animated: Bool) {
//Recieve notification
NotificationCenter.default.addObserver(self, selector: #selector(self.print1Method(notification:)), name: Notification.Name("callMethodPrint1FromVC2"), object: nil)
}
@objc func print1Method(notification: Notification) {
print("Notification came from VC 1")
}
@IBAction func backToVC1(_ sender: Any) {
let storyBoard = UIStoryboard(name: "Main", bundle: nil)
let vc2 = storyBoard.instantiateViewController(withIdentifier: "ViewController1Id") as? ViewController1
navigationController?.pushViewController(vc2!, animated: true)
}
//Remove notification object
deinit {
NotificationCenter.default.removeObserver(self, name: Notification.Name("callMethodPrint1FromVC2"), object: nil)
}
}
实际产量:
当我第一次和每次将ViewController1移动到ViewController2时,ViewController2中的print1Method方法必须调用。
但它的工作速度并没有那么快。
我的代码中是否有Anu问题,或者我遗漏了什么?
最佳答案
您正在初始化视图控制器之前发布通知。
调用vc2方法不需要发布通知。相反,直接调用方法。
在VC1中
@IBAction func nextButtonClicked(_ sender: Any) {
let storyBoard = UIStoryboard(name: "Main", bundle: nil)
let vc2 = storyBoard.instantiateViewController(withIdentifier:"ViewController2Id") as ViewController2
vc2.print1Method()
navigationController?.pushViewController(vc2!, animated: true)
}
}
在VC2中
func print1Method() {
print("Method called from VC 1")
}
同样对于后退按钮,你做得不对。只需从堆栈中弹出视图控制器
@IBAction func backToVC1(_ sender: Any) {
self.navigationController?.popViewController(animated: true)
}
关于ios - 从 View Controller 发布到另一个ViewController时,NotificationCenter第一次无法正常工作,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58074114/