Skip to content

Instantly share code, notes, and snippets.

@phranck
Last active November 13, 2022 22:40
Show Gist options
  • Star 20 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save phranck/7c3f4f8a420dd16148aedf2933d58877 to your computer and use it in GitHub Desktop.
Save phranck/7c3f4f8a420dd16148aedf2933d58877 to your computer and use it in GitHub Desktop.
A Swift view modifier to handle visibility of views for specific platforms
import SwiftUI
public struct Platform: OptionSet {
public var rawValue: UInt8
public static let iOS = Platform(rawValue: 1 << 0)
public static let macOS = Platform(rawValue: 1 << 1)
public static let tvOS = Platform(rawValue: 1 << 2)
public static let watchOS = Platform(rawValue: 1 << 3)
public static let all: Platform = [.iOS, .macOS, .tvOS, .watchOS]
#if os(iOS)
public static let current: Platform = .iOS
#elseif os(macOS)
public static let current: Platform = .macOS
#elseif os(tvOS)
public static let current: Platform = .tvOS
#elseif os(watchOS)
public static let current: Platform = .watchOS
#endif
public init(rawValue: UInt8) {
self.rawValue = rawValue
}
}
public extension View {
func visible(on platforms: Platform) -> some View {
modifier(PlatformVisibility(platforms: platforms))
}
}
// MARK: - Private API
private struct PlatformVisibility: ViewModifier {
var platforms: Platform = .current
func body(content: Content) -> some View {
platforms.contains(.current) ? content : nil
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment