Created
April 14, 2023 15:35
-
-
Save AlexeyTsutsoev/41f246e6098ffa5ad16dd4fb987e88cd to your computer and use it in GitHub Desktop.
Universal View for multiplatform SwiftUI Apps
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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