从 iOS 13.0 及更高版本开始,Apple 更改了默认显示 viewController 的方式。所以,ViewControllerA 中的 viewWillAppear 在关闭 ViewControllerB 后不会被调用。
确保在关闭 ViewControllerB 后调用 viewWillAppear 方法的一种方法是将 viewController 设置 modalPresentationStyle 呈现为 fullScreen 为:
let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(identifier: "ViewControllerB") as! ViewControllerB
vc.modalPresentationStyle = .fullScreen
self.present(vc, animated: true, completion: nil)
示例代码:
ViewControllerA.swift
class ViewControllerA: UIViewController {
private var username: String? {
UserDefaults.standard.string(forKey: "USERNAME")
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
print(username) //set this to desired view
}
@IBAction func goToViewControllerB(_ sender: UIButton) {
let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(identifier: "ViewControllerB") as! ViewControllerB
vc.modalPresentationStyle = .fullScreen
self.present(vc, animated: true, completion: nil)
}
}
ViewControllerB.swift
class ViewControllerB: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
UserDefaults.standard.set("John", forKey: "USERNAME")
}
@IBAction func dismiss(_ sender: Any) {
self.dismiss(animated: true, completion: nil)
}
}
如果您不想将 modalPresentationStyle 更改为 fullScreen,那么您可以在关闭 ViewControllerB 时使用闭包将数据传递给 ViewControllerA。