Skip to content

Instantly share code, notes, and snippets.

@MojtabaHs
Created September 24, 2020 13:20
Show Gist options
  • Save MojtabaHs/569b4b467aa7a4cea2afcb6736314b23 to your computer and use it in GitHub Desktop.
Save MojtabaHs/569b4b467aa7a4cea2afcb6736314b23 to your computer and use it in GitHub Desktop.
Representing both AppKit and UIKit Views inside the SwiftUI
#if os(macOS)
public typealias ViewRepresentable = NSViewRepresentable
public typealias NativeView = NSView
#elseif os(iOS)
public typealias ViewRepresentable = UIViewRepresentable
public typealias NativeView = UIView
#endif
public protocol ViewRepresentableHelper: ViewRepresentable {
associatedtype ViewType: NativeView
var configuration: (ViewType) -> () { get set }
func new() -> ViewType
}
public extension ViewRepresentableHelper {
func new() -> ViewType { ViewType() }
}
public extension ViewRepresentableHelper {
func makeView(_ context: Context) -> ViewType {
let view = new()
view.setContentHuggingPriority(.defaultHigh, for: .vertical)
view.setContentHuggingPriority(.defaultHigh, for: .horizontal)
return view
}
func updateView(_ view: ViewType, _ context: Context) { configuration(view) }
func makeUIView(context: Context) -> ViewType { makeView(context) }
func makeNSView(context: Context) -> ViewType { makeView(context) }
func updateUIView(_ uiView: ViewType, context: Context) { updateView(uiView, context) }
func updateNSView(_ nsView: ViewType, context: Context) { updateView(nsView, context) }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment