Last active
August 30, 2024 00:05
-
-
Save phranck/7c3f4f8a420dd16148aedf2933d58877 to your computer and use it in GitHub Desktop.
A Swift view modifier to handle visibility of views for specific platforms
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 | |
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