Skip to content

Instantly share code, notes, and snippets.

@AlexeyTsutsoev
Created April 14, 2023 15:35
Show Gist options
  • Save AlexeyTsutsoev/41f246e6098ffa5ad16dd4fb987e88cd to your computer and use it in GitHub Desktop.
Save AlexeyTsutsoev/41f246e6098ffa5ad16dd4fb987e88cd to your computer and use it in GitHub Desktop.
Universal View for multiplatform SwiftUI Apps
import SwiftUI
/// view for resolve different UI for MacOS and iOS
///
/// - Usage
/// ```
/// UniversalView {
/// ViewForIPhone
/// } desktop: {
/// ViewForMacOSOrIPad
/// }
/// ```
struct UniversalView<Phone, Desktop>: View where Phone: View, Desktop: View {
#if os(iOS)
@Environment(\.horizontalSizeClass) var horizontalSizeClass: UserInterfaceSizeClass?
#endif
let phoneView: Phone
let desktopView: Desktop
init(@ViewBuilder phone: () -> Phone, @ViewBuilder desktop: () -> Desktop) {
phoneView = phone()
desktopView = desktop()
}
var body: some View {
#if os(macOS)
desktopView
#else
if horizontalSizeClass == .compact {
phoneView
} else {
desktopView
}
#endif
}
}
struct UniversalView_Previews: PreviewProvider {
static var previews: some View {
UniversalView {
Text("This is a Iphone View")
} desktop: {
Text("This is IPad/MacOS view")
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment