Skip to content

Instantly share code, notes, and snippets.

@Rukh
Last active March 20, 2024 08:54
Show Gist options
  • Save Rukh/0841bae3094abbd7542838851e8a6ca4 to your computer and use it in GitHub Desktop.
Save Rukh/0841bae3094abbd7542838851e8a6ca4 to your computer and use it in GitHub Desktop.
EmbedSwiftUIView.swift
//
// Created by Dmitry Gulyagin on 24/11/2022.
//
import SwiftUI
/// Wrap SwiftUI view into the container. You can change 'var' properties of the View, and SwiftUI will animate all changes
@dynamicMemberLookup
public final class EmbedSwiftUIView<RootView> where RootView : View {
private let controller: UIHostingController<RootView>
public var view: UIView { controller.view }
public init(rootView: RootView) {
controller = UIHostingController(rootView: rootView)
controller.view.backgroundColor = .clear
}
public subscript<Value>(dynamicMember keyPath: WritableKeyPath<RootView, Value>) -> Value {
get {
return controller.rootView[keyPath: keyPath]
}
set {
var view = controller.rootView
view[keyPath: keyPath] = newValue
controller.rootView = view
}
}
}
public extension View {
func makeEmbeded() -> EmbedSwiftUIView<Self> {
EmbedSwiftUIView(rootView: self)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment