Skip to content

Instantly share code, notes, and snippets.

@finestructure
Last active April 22, 2020 08:18
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 finestructure/f3ecf70c2e541276267da94602b46d0c to your computer and use it in GitHub Desktop.
Save finestructure/f3ecf70c2e541276267da94602b46d0c to your computer and use it in GitHub Desktop.
// See: https://www.swiftbysundell.com/tips/inline-wrapping-of-uikit-or-appkit-views-within-swiftui/
import SwiftUI
#if os(iOS)
public struct Wrap<Wrapped: UIView>: UIViewRepresentable {
public typealias Updater = (Wrapped, Context) -> Void
var makeView: () -> Wrapped
var update: (Wrapped, Context) -> Void
public init(_ makeView: @escaping @autoclosure () -> Wrapped,
updater update: @escaping Updater) {
self.makeView = makeView
self.update = update
}
public func makeUIView(context: Context) -> Wrapped {
makeView()
}
public func updateUIView(_ view: Wrapped, context: Context) {
update(view, context)
}
}
extension Wrap {
public init(_ makeView: @escaping @autoclosure () -> Wrapped,
updater update: @escaping (Wrapped) -> Void) {
self.makeView = makeView
self.update = { view, _ in update(view) }
}
public init(_ makeView: @escaping @autoclosure () -> Wrapped) {
self.makeView = makeView
self.update = { _, _ in }
}
}
#endif
#if os(macOS)
public struct Wrap<Wrapped: NSView>: NSViewRepresentable {
public typealias Updater = (Wrapped, Context) -> Void
var makeView: () -> Wrapped
var update: (Wrapped, Context) -> Void
public init(_ makeView: @escaping @autoclosure () -> Wrapped,
updater update: @escaping Updater) {
self.makeView = makeView
self.update = update
}
public func makeNSView(context: Context) -> Wrapped {
makeView()
}
public func updateNSView(_ view: Wrapped, context: Context) {
update(view, context)
}
}
extension Wrap {
public init(_ makeView: @escaping @autoclosure () -> Wrapped,
updater update: @escaping (Wrapped) -> Void) {
self.makeView = makeView
self.update = { view, _ in update(view) }
}
public init(_ makeView: @escaping @autoclosure () -> Wrapped) {
self.makeView = makeView
self.update = { _, _ in }
}
}
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment