问题
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