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

2      

Hacking with Swift is sponsored by RevenueCat.

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

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.