Detect Orientation Changes in Swift Playgrounds

What is the correct way to detect device orientation changes in Swift Playgrounds? One of the views in my Playground Book needs to be manually adjusted when the device rotates, but it doesn't appear that any of the standard approaches are working. It seems like this question has been asked a few times in the past (see https://forums.developer.apple.com/search.jspa?q=orientation+playground) with no concrete answers as of yet. For my WWDC 2019 scholarship submission, I'd like to have this running to ensure the playground looks great at all times, even after an iPad is rotated in the Playgrounds app.


I've tried adding code in:

func viewDidLayoutSubviews()

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

func didRotate(from fromInterfaceOrientation: UIInterfaceOrientation)

It seems like viewDidLayoutSubviews() works when testing the Playground Book simulator app, but when actually testing the .playgroundbook file in the Swift Playgrounds app the orientation changes are not correctly detected.

If anyone has found a way to detect these changes, your support would be greatly appreciated!

Replies

Are you using Auto Layout? I've been having some UI layout issues myself (see UI layout issues on iOS playground), and I haven't figured them out yet, but I've got a bunch of Auto Layout code in my playground live view's view controller, and there's some weird behavior happening.

I encountered the same problem.


Sadly, we cannot get the orientation when the codes are running in the Playground.


Neither can we use `UIApplication.shared.statusBarOrientation` nor `UIDevice.current.orientation`.


You can try using `CoreMotion` and access the raw data of the accelerator, and do the math.


But, it's not stable and efficient.


And it may results unexpectedly under some circumstances.