Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marcuswestin/81a3dd06c2b7c4c5236fa37990f33afe to your computer and use it in GitHub Desktop.
Save marcuswestin/81a3dd06c2b7c4c5236fa37990f33afe to your computer and use it in GitHub Desktop.
An approach for simplified wrapping of AppKit and UIKit views in SwiftUI
protocol ViewWrapper {
associatedtype ViewType: OSView
typealias Context = OSViewRepresentableContext<WrapView<Self>>
func makeView(_ context: Context) -> ViewType
func updateView(_ view: ViewType, _ context: Context)
func wrapped() -> WrapView<Self>
}
struct WrapView<Wrapper: ViewWrapper>: OSViewRepresentable {
let wrapper: () -> Wrapper
internal func makeCoordinator() -> Wrapper {
return wrapper()
}
#if os(macOS)
internal func makeNSView(context: NSViewRepresentableContext<WrapView>) -> Wrapper.ViewType {
context.coordinator.makeView(context)
}
internal func updateNSView(_ view: Wrapper.ViewType, context: NSViewRepresentableContext<WrapView>) {
context.coordinator.updateView(view, context)
}
#elseif os(iOS)
internal func makeUIView(context: NSViewRepresentableContext<WrapView>) -> Wrapper.ViewType {
context.coordinator.makeView(context)
}
internal func updateUIView(_ view: Wrapper.ViewType, context: NSViewRepresentableContext<WrapView>) {
context.coordinator.updateView(view, context)
}
#endif
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment