Last active
April 22, 2020 08:18
-
-
Save finestructure/f3ecf70c2e541276267da94602b46d0c to your computer and use it in GitHub Desktop.
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
// 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