How to detect whether targetEnvironment is iPadOS in SwiftUI?

一世执手 提交于 2020-06-12 07:28:30

问题


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


回答1:


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")
        }
    }



回答2:


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))
}


来源:https://stackoverflow.com/questions/57652242/how-to-detect-whether-targetenvironment-is-ipados-in-swiftui

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!