Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect whether targetEnvironment is iPadOS in SwiftUI?

Tags:

swift5

swiftui

I'd like to display different views when building for iOS and iPadOS. Currently, I know I can do

import SwiftUI

struct ContentView: View {
    #if targetEnvironment(macCatalyst)
    var body: some View {
        Text("Hello")
    }
    #else
    var body: some View {
        Text("Hello")
    }
    #endif
}

to display different views between macOS and iPadOS/iOS (introduced in Swift 4/5). But how do I differentiate between the latter? I can't seem to use targetEnvironment...

like image 245
cyril Avatar asked Aug 26 '19 05:08

cyril


3 Answers

I add the following code as an extension of UIDevice.

extension UIDevice {
    static var isIPad: Bool {
        UIDevice.current.userInterfaceIdiom == .pad
    }
    
    static var isIPhone: Bool {
        UIDevice.current.userInterfaceIdiom == .phone
    }
}

Now anywhere I can call UIDevice.isIPad or UIDevice.isIPhone to know which device is it.

like image 198
Mahmud Ahsan Avatar answered Nov 04 '22 02:11

Mahmud Ahsan


I use this in my code:

    private var idiom : UIUserInterfaceIdiom { UIDevice.current.userInterfaceIdiom }
    private var isPortrait : Bool { UIDevice.current.orientation.isPortrait }

Then you can do this:

    var body: some View {
        NavigationView {
            masterView()

            if isPortrait {
                portraitDetailView()
            } else {
                landscapeDetailView()
            }
        }
    }

    private func portraitDetailView() -> some View {
        if idiom == .pad {
            return Text("iPadOS")
        } else {
            return Text("iOS")
        }
    }
like image 40
caram Avatar answered Nov 04 '22 02:11

caram


To return different view types you can use AnyView eraser type:

if UIDevice.current.userInterfaceIdiom == .pad {
    return AnyView(Text("Hello, World!"))
} else {
    return AnyView(Rectangle().background(Color.green))
}
like image 43
Zontag Avatar answered Nov 04 '22 00:11

Zontag