UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

How to determine an iPad's portrait/landscape orientation for different views

Forums > SwiftUI

Piecing together various clues across the internet from techniques that didn't work or were ungainly, I've figured out a tiny bit of code that might help others who, like me, have been trying to figure out a way to determine an iPad's orientation for presenting different UI arrangements based on whether a user is using it in landscape or portrait. (SizeClass works with iPhone, but iPad thinks both P and L orientations = .regular).

For example, if you have a ContentViewPortrait struct for portrait orientation and a ContentViewLandscape struct for landscape orientation, then you could use a ContentView struct like this:

struct ContentView: View {
  @Environment(\.horizontalSizeClass) var orientation
    var body: some View {
        GeometryReader { ruler in
            if ruler.size.width < ruler.size.height || orientation == .compact {
            } else {

@Environment(\.horizontalSizeClass) var orientation and || orientation == .compact are (only) necessary if you have the "Support multiple windows" option checked in the General/Info panel, because Slide Over and Split View seem to come along for the ride.


BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

Unknown user

You are not logged in

Log in or create account

Link copied to your pasteboard.