UIViewController selective Autorotation with Size classes
Asked Answered
N

0

0

The new size classes based Autorotation is a pain if you want custom behavior. Here are my requirements and flow:

  • View Controller 1(VC1) modally presents View Controller 2 (VC2)
  • VC1 only supports landscape, portrait, or both depending on user settings (achieved via supportedInterfaceOrientations). For this example, we assume it is locked to landscape,

  • VC 2 supports both landscape & portrait

I use Size classes and in View Controller 1, I check for statusBarOrientation in viewWillTransition(to size...) to configure interface elements positioning & other customizations.

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

    let orientation = UIApplication.shared.statusBarOrientation

    NSLog("View will transition to \(size), \(orientation.rawValue)")
    super.viewWillTransition(to: size, with: coordinator)


    coordinator.animate(alongsideTransition: { [unowned self] (_) in
    ....
    }
}

This works, except when VC 2 is presented and the device is rotated. VC 1 is all messed up when VC 2 is dismissed. To be sure, I would like to refresh layout of View Controller 1 when it appears. How do I do that? I tried UIViewController.attemptRotationToDeviceOrientation() but it doesn't force the autorotation methods to be called again.

EDIT: As can be seen, in VC1 I check for statusBarOrientation to determine interface orientation. That poses a problem, because statusBarOrientation gets changed to portrait when VC2 rotates to portrait mode. And viewWillTransition to size gets invoked on VC1 at the same time where I force layout to portrait mode.

Negris answered 18/11, 2018 at 19:9 Comment(2)
couldn't you refresh layout on viewWillAppear?Graziano
It only works in viewDidAppear, however there are issues with it. There is abrupt change in interface that is seen by putting it in viewDidAppear which looks weird. The previous deprecated APIs of autorotation has no such issue.Negris

© 2022 - 2024 — McMap. All rights reserved.