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

SOLVED: UITraitCollection: How to detect device orientation (Especially iPad)

Forums > iOS

iPad has .regularWidth and .regularHeight for both landscape and portrait orientations. How can I determine the iPad being in landscape or portrait ?

3      

3      

Still a question: traitCollection is available on a viewController, but I want to use it more generic and reusable in more place, so I thought about something like

///Helper to determine device type and orientation
enum DeviceType {
    private var traitCollection: UITraitCollection {
        return UITraitCollection()
    }
    static var isIpadLandscape: Bool {
        return (traitCollection.horizontalSizeClass == .regularWidth && traitCollection.verticalSizeClass == .regularHeight) &&
                UIApplication.shared.statusBarOrientation.isLandscape
    }
}

This doesn't work , any hints to push me in the right direction ?

3      

This works:


///Helper to determine device type and orientation
enum DeviceTypeAndOrientation {
    static var isIpad: Bool {
        return UIView().traitCollection.horizontalSizeClass == .regular && UIView().traitCollection.verticalSizeClass == .regular
    }

    static var isLandscape: Bool {
        return UIApplication.shared.windows.first?.windowScene?.interfaceOrientation.isLandscape ?? false
    }
}

This works for me for now, but ... ... is this a neat way of doing things, or is it not done? Also I've read on several sites that using screen orientation is not done anymore on iOS devices, especially on iPads, in regards to multitasking/window, etc. Could someone point me in a direction of a better way to do this ?

3      

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

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.