A headache-inducing scenario: I’m working on a view controller, and I realise that in order to support landscape and portrait modes, I’m going to need to provide two different layouts.
So, I create two different views within the nib, one portrait, one landscape, each with the same view hierarchy, but with a different layout.
When the orientation changes, I set self.view
to the appropriate view. I initialise both views on load, and keep both of them synced to properly reflect the app’s state — basically, I’m double-handling everything, which bloats my code and increases the chance I’ll make a mistake.
So, here’s an easier way: Rather than maintaining two separate view hierarchies and switching between them when the orientation changes, why not just change the layout of one single view hierarchy? The only changes between the portrait and landscape views are layout changes, so if we can extract just the layout information from each view, then we don’t have to worry about maintaining both view hierarchies.
Basically, we’re talking about using each view version as a layout template only.
That’s what TPMultiLayoutViewController class does. It’s a drop-in UIViewController subclass that automatically manages switching between different view layouts for portrait and landscape orientations, without the need to maintain view state across two different view hierarchies.
It works by defining portraitView
and landscapeView
outlets which it traverses upon loading the nib. It matches each subview element to its counterpart in the other layout (based on tag, target/action, title, etc.), and stores just the layout attributes of each element.
Then, when the orientation changes, the view hierarchy is traversed and these layouts are applied to each subview.
To use it,
- Set the superclass for your view controller to
TPMultiLayoutViewController
.
- In Interface Builder, create two different views: one for portrait orientation, and one for landscape orientation.
- Attach your portrait orientation root view to the “portraitView” outlet, and the landscape orientation root view to the “landscapeView” outlet.
- Attach one of the views (whichever you prefer) to the “view” outlet, and connect any actions and outlets from that view.
Grab it from the TPMultiLayoutViewController GitHub repository, and let me know what you think.
The Amazing Audio Engine 2 Sample App demo
Here’s a demo of the TAAE2 sample app – full source code with The Amazing Audio Engine 2.