Created
July 13, 2021 08:01
-
-
Save odrobnik/9bd019e0048d0518dd8ab08544d73b84 to your computer and use it in GitHub Desktop.
Platform-specific modifier application
This file contains hidden or 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 | |
struct Platform: OptionSet | |
{ | |
let rawValue: Int | |
static let iOS = Platform(rawValue: 1<<0) | |
static let tvOS = Platform(rawValue: 1<<1) | |
static let watchOS = Platform(rawValue: 1<<2) | |
static var current: Platform | |
{ | |
var tmp: Platform = [] | |
#if os(iOS) | |
tmp.insert(.iOS) | |
#endif | |
#if os(watchOS) | |
tmp.insert(.watchOS) | |
#endif | |
#if os(tvOS) | |
tmp.insert(.tvOS) | |
#endif | |
return tmp | |
} | |
} | |
struct PlatformSpecificModifier<M: ViewModifier>: ViewModifier | |
{ | |
let platform: Platform | |
let modifier: M | |
@ViewBuilder | |
func body(content: Content) -> some View | |
{ | |
if Platform.current.intersection(platform) != [] | |
{ | |
content.modifier(modifier) | |
} | |
else | |
{ | |
content | |
} | |
} | |
} | |
extension View | |
{ | |
func platformSpecific<M: ViewModifier>(_ platform: Platform, modifier: M) -> some View | |
{ | |
self.modifier(PlatformSpecificModifier(platform: platform, modifier: modifier)) | |
} | |
@ViewBuilder | |
func onlyOn<V: View>(_ platform: Platform, modified: (View)->V) -> some View | |
{ | |
if Platform.current.intersection(platform) != [] | |
{ | |
modified(self) | |
} | |
else | |
{ | |
self | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment