Skip to content

Instantly share code, notes, and snippets.

@aerobounce
Created February 25, 2021 18:49
Show Gist options
  • Save aerobounce/3710e986f6a1b816b4b01c0b703e6dad to your computer and use it in GitHub Desktop.
Save aerobounce/3710e986f6a1b816b4b01c0b703e6dad to your computer and use it in GitHub Desktop.
import AppKit
import SwiftUI
// MARK: Wrap
public struct Wrap<Wrapped: NSView>: NSViewRepresentable {
private var makeView: () -> Wrapped
private var update: (Wrapped, Context) -> Void
public init(_ makeView: @escaping @autoclosure () -> Wrapped,
updater update: @escaping (Wrapped, Context) -> Void) {
self.makeView = makeView
self.update = update
}
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
update = { _, _ in }
}
public func makeNSView(context: Context) -> Wrapped {
makeView()
}
public func updateNSView(_ view: Wrapped, context: Context) {
update(view, context)
}
}
// MARK: WrapController
public struct WrapController<Wrapped: NSViewController>: NSViewControllerRepresentable {
private var makeView: () -> Wrapped
private var update: (Wrapped, Context) -> Void
public init(_ makeView: @escaping @autoclosure () -> Wrapped,
updater update: @escaping (Wrapped, Context) -> Void) {
self.makeView = makeView
self.update = update
}
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
update = { _, _ in }
}
public func makeNSViewController(context: Context) -> Wrapped {
makeView()
}
public func updateNSViewController(_ nsViewController: Wrapped, context: Context) {
update(nsViewController, context)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment