Created
June 27, 2023 13:05
-
-
Save insidegui/147a90ef8deeebd8f4952216a7ef80c4 to your computer and use it in GitHub Desktop.
A protocol that abstracts UIViewRepresentable/NSViewRepresentable allowing for a single implementation for UIKit and AppKit platforms
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(watchOS) | |
#if canImport(UIKit) | |
public typealias PlatformViewRepresentableType = UIViewRepresentable | |
#else | |
public typealias PlatformViewRepresentableType = NSViewRepresentable | |
#endif // canImport(UIKit) | |
public protocol PlatformViewRepresentable: PlatformViewRepresentableType { | |
associatedtype PlatformViewType | |
func makePlatformView(context: Context) -> PlatformViewType | |
func updatePlatformView(_ platformView: PlatformViewType, context: Context) | |
} | |
#if canImport(UIKit) | |
public extension PlatformViewRepresentable where UIViewType == PlatformViewType { | |
func makeUIView(context: Context) -> UIViewType { | |
makePlatformView(context: context) | |
} | |
func updateUIView(_ uiView: UIViewType, context: Context) { | |
updatePlatformView(uiView, context: context) | |
} | |
} | |
#else | |
public extension PlatformViewRepresentable where NSViewType == PlatformViewType { | |
func makeNSView(context: Context) -> NSViewType { | |
makePlatformView(context: context) | |
} | |
func updateNSView(_ nsView: NSViewType, context: Context) { | |
updatePlatformView(nsView, context: context) | |
} | |
} | |
#endif // canImport(UIKit) | |
#endif // os(watchOS) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Your own custom
UIView
orNSView
has to be platform-independent as well.Example: