Created
August 10, 2022 18:13
-
-
Save insidegui/97d821ca933c8627e7f614bc1d6b4983 to your computer and use it in GitHub Desktop.
Protocol that automatically adds UIViewRepresentable or NSViewRepresentable conformance to implementers according to the current platform
This file contains 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 | |
#if os(iOS) || os(tvOS) | |
public typealias PlatformView = UIView | |
public typealias PlatformViewRepresentable = UIViewRepresentable | |
#elseif os(macOS) | |
public typealias PlatformView = NSView | |
public typealias PlatformViewRepresentable = NSViewRepresentable | |
#endif | |
/// Implementers get automatic `UIViewRepresentable` conformance on iOS | |
/// and `NSViewRepresentable` conformance on macOS. | |
public protocol PlatformAgnosticViewRepresentable: PlatformViewRepresentable { | |
associatedtype PlatformViewType | |
func makePlatformView(context: Context) -> PlatformViewType | |
func updatePlatformView(_ platformView: PlatformViewType, context: Context) | |
} | |
#if os(iOS) || os(tvOS) | |
public extension PlatformAgnosticViewRepresentable where UIViewType == PlatformViewType { | |
func makeUIView(context: Context) -> UIViewType { | |
makePlatformView(context: context) | |
} | |
func updateUIView(_ uiView: UIViewType, context: Context) { | |
updatePlatformView(uiView, context: context) | |
} | |
} | |
#elseif os(macOS) | |
public extension PlatformAgnosticViewRepresentable where NSViewType == PlatformViewType { | |
func makeNSView(context: Context) -> NSViewType { | |
makePlatformView(context: context) | |
} | |
func updateNSView(_ nsView: NSViewType, context: Context) { | |
updatePlatformView(nsView, context: context) | |
} | |
} | |
#endif |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment