Skip to content

Instantly share code, notes, and snippets.

@odrobnik
Created July 13, 2021 08:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save odrobnik/9bd019e0048d0518dd8ab08544d73b84 to your computer and use it in GitHub Desktop.
Save odrobnik/9bd019e0048d0518dd8ab08544d73b84 to your computer and use it in GitHub Desktop.
Platform-specific modifier application
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