viewWillTransitionToSize Calls Wrong ViewController in TabBarController

693 Views Asked by At

I have tabBarController application with 4 viewcontrollers. This application is landscape orientation enabled so I have viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id)coordinator in each viewcontroller.m file to control the orientation changes.

The problem I'm having, is when I change the device orientation while in the 3rd viewcontroller, the viewWillTransitionToSize in the 2nd viewcontroller is called so the wrong code is ran.

How is it possible that the 2nd viewcontroller's viewWillTransitionToSize is even called? Especially, when it hasn't even been loaded yet. I know it hasn't been loaded because I NSLog it's viewDidLoad and it shows when I change orientation from the 3rd viewcontroller.

Additional Info: There is no code in the 3rd viewcontroller's viewWillTransitionToSize, viewWillAppear, viewWillDisappear, etc. that would reference the 2nd viewcontroller.

I'm using Xcode 8.2.1 and Objective-C code. Please help, thanks.

2

There are 2 best solutions below

0
On

Test to see which UIViewController is the selected UIViewController before handling the transition.

In Swift:

override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator)
{
    guard self == tabBarController?.selectedViewController else { return }

    // handle transition here
}

In my situation, the UIViewController was embedded in a UINavigationController so I had to handle it slightly differently:

override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator)
{
    guard self.navigationController == tabBarController?.selectedViewController else { return }

    // handle transition here
}
2
On

I replaced each instance of

viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id)coordinator 

with

willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration 

to avoid the aforementioned issue with viewWillTransitionToSize...