31

我正在从一个名为 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 呢?

4

4 回答 4

40

您需要设置正确的presentationStyle。如果您希望您的presentedController 将是fullScreen 并将其称为之前的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)
于 2018-06-28T18:21:27.110 回答
5

在 iOS 13 中,如果您正在展示一个视图控制器并且当您回来时 viewWillAppear 不会被调用。我已将其从现在更改为推送视图控制器,并且现在正在调用方法。

于 2020-02-19T07:25:43.463 回答
3

将演示样式更改为 .fullScreen 可以工作,但会更改呈现的视图控制器的外观。如果您想避免这种情况,您可以覆盖呈现的视图控制器中的 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)
      }
 }
于 2021-12-02T12:20:12.487 回答
0

如果呈现的 viewController 是半屏,那么您将不得不在侧面呈现的视图控制器的 viewWillDisappear 中手动调用呈现 viewController 的 viewWillAppear。将以下代码添加到您的呈现视图控制器。

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)' 才能让您的展示视图控制器viewWillAppear每次都执行。

于 2022-02-09T18:13:56.730 回答