NEW: My new book Pro SwiftUI is out now – level up your SwiftUI skills today! >>

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 {
                ContentViewPortrait()
            } else {
                ContentViewLandscape()
            }
        }
    }
}

@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.

   

Hacking with Swift is sponsored by Play

SPONSORED Play is the first native iOS design tool created for designers and engineers. You can install Play for iOS and iPad today and sign up to check out the Beta of our macOS app with SwiftUI code export. We're also hiring engineers!

Click to learn more about Play!

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

Reply to this topic…

You need to create an account or log in to reply.

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.