Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UINavigationControllerDelegate‘s didShowViewController method was called twice

class ViewController: UIViewController, UINavigationControllerDelegate {

      override func viewDidLoad() {
         super.viewDidLoad()
         navigationController!.delegate = self
      }

      func navigationController(navigationController: UINavigationController, didShowViewController viewController: UIViewController, animated: Bool) {
         print("showViewController")
      }

      func navigationController(navigationController: UINavigationController, willShowViewController viewController: UIViewController, animated: Bool) {
         print("sss")
      }

      func update() {
         let vc = SecondViewController()
         navigationController!.pushViewController(vc, animated: true)
      }
}

this is the first controller of my demo , and in console:

sss
showViewController
showViewController

the "didShowViewController" was called twice. I'm not sure what's going on

-----------------some test----------------------

I add some log in these method of controller : loadView,viewDidLoad ,viewWillAppear,viewDidAppear , and the order of these log is:

loadView
viewDidLoad
viewWillAppear
will:<NaviDemo.ViewController: 0x7fe8c9533050>
<NaviDemo.ViewController: 0x7fe8c9533050>
viewDidAppear
<NaviDemo.ViewController: 0x7fe8c9533050>
like image 540
belle tian Avatar asked Dec 25 '15 09:12

belle tian


1 Answers

I hit the same issue in my code. I was able to work around it by waiting until viewDidAppear to set the navigation delegate instead of setting it in viewDidLoad. To translate it to your example:

override func viewDidLoad() {
   super.viewDidLoad()
}

// ...

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    navigationController!.delegate = self
}
like image 172
wulong Avatar answered Nov 07 '22 04:11

wulong