Created
April 14, 2021 05:41
-
-
Save brunow/69763de7793d1d01e2f1f124cec55d4c to your computer and use it in GitHub Desktop.
SwiftUI os specific modifier
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
/// After reading an article from Antoine v.d. SwiftLee @twannl about conditional view modifier, I had an idea to improve my code I write for specific OS. | |
/// https://www.avanderlee.com/swiftui/conditional-view-modifier | |
extension Bool { | |
static var iOS: Bool { | |
#if os(iOS) | |
return true | |
#else | |
return false | |
#endif | |
} | |
static var macOS: Bool { | |
#if os(macOS) | |
return true | |
#else | |
return false | |
#endif | |
} | |
static var watchOS: Bool { | |
#if os(watchOS) | |
return true | |
#else | |
return false | |
#endif | |
} | |
static var tvOS: Bool { | |
#if os(tvOS) | |
return true | |
#else | |
return false | |
#endif | |
} | |
} | |
struct ViewPlatformOptions: OptionSet { | |
static let iOS = ViewPlatformOptions(rawValue: 1) | |
static let macOS = ViewPlatformOptions(rawValue: 1 << 1) | |
static let watchOS = ViewPlatformOptions(rawValue: 1 << 2) | |
static let tvOS = ViewPlatformOptions(rawValue: 1 << 2) | |
let rawValue: Int8 | |
init(rawValue: Int8) { | |
self.rawValue = rawValue | |
} | |
} | |
@ViewBuilder | |
func `if`<Content: View>(_ platforms: ViewPlatformOptions, content: (Self) -> Content) -> some View { | |
if platforms.contains(.iOS) && Bool.iOS || | |
platforms.contains(.macOS) && Bool.macOS || | |
platforms.contains(.watchOS) && Bool.watchOS || | |
platforms.contains(.tvOS) && Bool.tvOS { | |
content(self) | |
} else { | |
self | |
} | |
} | |
Text("If") | |
.if([.iOS, .macOS]) { | |
$0.font(Font.title.weight(.bold)) | |
} | |
Text("If") | |
.if(.iOS) { | |
$0.font(Font.title.weight(.bold)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment