Last week, I spoke at and attended iOSDevCampDC, where I had the pleasure of listening to @atomicbird‘s great talk on StackViews. I already wrote about how easy it is to do a simple animation with StackView, but I was also impressed by how easy it is to support screen rotation from Portrait to Landscape using StackViews.
As an example, take a simple view that has an image and some text. It looks great in Portrait, but when the screen is rotated, it’s not quiet as nice…
Well, with only one simple StackView change in the Storyboard (no code needed), you can have a rotation that makes sense:
The initial setup is a simple Vertical StackView that has an ImageView and a TextView in it:
The One Weird Trick
The key here is that we need to change the StackView from being Vertical to being Horizontal when the orientation changes to Landscape.
To see this in action, I recommend changing to Landscape mode in the Storyboard (love this chart in Xcode 8!):
Notice that the storyboard in Xcode 8 conveniently tells you that in Landscape, the Height is Compact. Seriously loving Xcode 8 because of this!
Now the trick is to set the StackView to be Horizontal when the Height is Compact. To do that, select the StackView, and go to the Attributes Inspector. You’ll see the tiniest + under the StackView Axis property – click on it!
Now select Any Width -> Compact Height -> Any Gamut:
The key here is of course the Compact Height. Now you can change the StackView layout to Horizontal in Compact Height mode!
That’s it! You will immediately see the change right there in the Storyboard without having to run the app:
One thing to note here is that there is a bug in the Storyboard – when you change the orientation, there might be a warning about your layout. Just change the hugging priority or compression (doesn’t matter which one) by one and back again in your StackView AutoLayout, and it’ll fix the warning ¯\_(ツ)_/¯
I haven’t played much with changing my layout for different rotations / screens, so this is definitely a good thing to keep in mind. It doesn’t sound as fun to have to manually completely change AutoLayout for different compression sizes, especially when a product manager asks you to insert “just one small thing” in there… Thx again @atomicbird for sharing this small but very powerful trick with us!
Join me for a Swift Community Celebration 🎉 in New York City on September 1st and 2nd. Use code NATASHATHEROBOT to get $100 off!