Swift 关闭视图控制器后未调用 viewWillAppear

Swift viewWillAppear not being called after dismissing view controller

我正在从一个名为 HomeController 的视图控制器中呈现一个视图控制器,如下所示:

let viewController = self.storyboard?.instantiateViewController(withIdentifier: "LoginController") as! LoginController

let navigationController: UINavigationController = UINavigationController(rootViewController: viewController)

present(navigationController, animated: true, completion: nil)

在呈现的视图控制器中,LoginController 有时会被关闭:

self.dismiss(animated: true, completion: nil)

但是当它返回到 HomeController 时它并没有调用 viewWillAppear,当它返回到 HomeController 时我真的需要检查它的状态,那么当 LoginController 关闭视图时我如何调用 viewWillAppear?

您需要设置正确的presentationStyle。如果您希望您的 presentedController 是全屏的,并将其称为前一个 viewWillAppear,那么您可以使用“.fullScreen

let viewController = self.storyboard?.instantiateViewController(withIdentifier: "LoginController") as! LoginController

let navigationController: UINavigationController = UINavigationController(rootViewController: viewController)

navigationController.modalPresentationStyle = .fullScreen

present(navigationController, animated: true, completion: nil)

在 iOS 13 中,如果您正在呈现视图控制器并且当您返回时,不会调用 viewWillAppear。 我已经将它从 present 更改为 push view controller 并且现在正在调用方法。

将呈现样式更改为 .fullScreen 有效,但会更改呈现的视图控制器的外观。如果您想避免这种情况,您可以重写所提供的 viewcontroller 中的 viewWillDisappear 方法,并在其中添加 presentingViewController?.viewWillAppear(true).

示例:

 class ViewControllerA: UIViewController {
 
      override func viewDidLoad() {
          super.viewDidLoad()
          
          //put the presenting action wherever you want

          let vc = ViewControllerB()
          navigationController.present(vc, animated: true)
      }

      override func viewWillAppear(_ animated: Bool) {
           super.viewWillAppear(animated) 
           //refresh Whatever 
      }
 }

 class ViewControllerB: UIViewController {
 
      override func viewDidLoad() {
          super.viewDidLoad()
      }

      override func viewWillDisappear(_ animated: Bool) {
          super.viewWillDisappear(animated)

          //this will call the viewWillAppear method from ViewControllerA  

          presentingViewController?.viewWillAppear(true)
      }
 }

如果 presented viewController 是半屏那么你将不得不在 side presented view controller 的 viewWillDisappear 中手动调用 presenting viewController 的 viewWillAppear。 将以下代码添加到您的 Presented 视图控制器。

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    presentingViewController?.viewWillDisappear(true)
}    

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
    presentingViewController?.viewWillAppear(true)
}

注意:您必须调用 'presentingViewController?.viewWillDisappear(true)' 才能让 Presenting 视图控制器 viewWillAppear 每次都执行。