iosswiftuiviewuiviewcontrollerviewwilltransitiontosize

Why is viewWillTransition(to size:...) not working if I navigate away from and back to the View Controller?


I have a UIView subclass called myView that is supposed reconfigure itself when the device orientation changes. I'm using the viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) method in the UIViewController to call the setUp() method that reconfigures the view. The problem I am having is that it works the first time I load that particular view controller, but if I navigate away then back to it the code no longer works. What's wrong? The code is as follows:

@IBOutlet weak var myView: UIView!
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
    self.myView.setUp()
}

If I use the deprecated method didRotate(from fromInterfaceOrientation: UIInterfaceOrientation) instead, the code works properly every time.


Solution

  • So, I still haven't figured out why the original problem is happening, but I did figure out a workaround. Ordinarily it would be possible to just calculate the orientation based on UIScreen.main.bounds in the viewDidLayoutSubviews() method, but I have a timer that is firing at the screen refresh rate, so that method is being called 60 times/second, and my myView.setUp() method is way too processor intensive for that to be workable. So, I've given my UIViewController an orientation property with a setter observer, with that property being calculated and set within viewDidLayoutSubviews(). The setter observer then calls the setUp() method if the orientation changes. I'm still curious why the other method isn't working, but the workaround will do.