Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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