Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS viewWillTransitionToSize and device orientation

I'm using viewWillTransitionToSize to detect when a device is rotating to landscape. Depending on the target size, I can detect if heading for landscape and adjust my traits as required...

override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {

    if size.width > size.height {
        self.setOverrideTraitCollection(UITraitCollection(horizontalSizeClass: UIUserInterfaceSizeClass.Regular), forChildViewController: viewController)
    }
    else{
        self.setOverrideTraitCollection(nil, forChildViewController: viewController)
    }

    super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator)
}

However, I want to be able to detect whether my device is transitioning to landscape-left or landscape-right. This will allow me to create different behaviours or views, depending on specific orientation of device. (left or right).

Is this possible without using any deprecated functions?

I thought of using status-bar orientation...

    let orientation = UIApplication.sharedApplication().statusBarOrientation;
    if( orientation == UIInterfaceOrientation.LandscapeLeft )
    {
        // Do something
    }
    else if( orientation == UIInterfaceOrientation.LandscapeRight )
    {
        // Do something else
    }

...but that doesn't help because this appears to give the 'old' status orientation.

How can I get the specific target orientation?

like image 764
Fittoburst Avatar asked Mar 02 '15 22:03

Fittoburst


1 Answers

You can get orientation while rotating use UIViewControllerTransitionCoordinator as follows:

override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
    super.viewWillTransition(to: size, with: coordinator)

    // will execute before rotation

    coordinator.animate(alongsideTransition: { (context: UIViewControllerTransitionCoordinatorContext) in

        // will execute during rotation
        let orientation = UIApplication.shared.statusBarOrientation
        if orientation == .landscapeLeft 
        {
            // Do something
        } 
        else if orientation == .landscapeRight 
        {
            // Do something else
        }
    }) { (context: UIViewControllerTransitionCoordinatorContext) in
        // will execute after rotation
    }
}
like image 117
Quang Tran Avatar answered Oct 10 '22 05:10

Quang Tran