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...
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.
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")
}
}
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))
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With