Last active
January 3, 2023 22:16
-
-
Save nathanborror/c9b92591be70639ab82f757686af0266 to your computer and use it in GitHub Desktop.
Custom UIKit view with child SwiftUI views
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
import UIKit | |
import SwiftUI | |
import PlaygroundSupport | |
// CustomParentView is a custom UIKit view. Its Coordinator can be used | |
// to manage delegates if needed (e.g. UIContextMenuInteractionDelegate). | |
struct CustomParentView<Content: View>: UIViewRepresentable { | |
let content: UIView | |
@inlinable init(@ViewBuilder content: () -> Content) { | |
self.content = UIHostingController(rootView: content()).view | |
} | |
func makeCoordinator() -> Coordinator { | |
Coordinator(self) | |
} | |
func makeUIView(context: Context) -> UIView { | |
let view = UIView() | |
view.backgroundColor = .lightGray | |
content.frame = view.bounds | |
content.autoresizingMask = [.flexibleWidth, .flexibleHeight] | |
content.backgroundColor = .clear // unfortunate | |
view.addSubview(content) | |
return view | |
} | |
func updateUIView(_ uiView: UIView, context: Context) { | |
// nothing to update | |
} | |
class Coordinator: NSObject { | |
var view: CustomParentView | |
init(_ view: CustomParentView) { | |
self.view = view | |
} | |
} | |
} | |
// ContentView is an example of how to use our CustomParentView | |
// with child SwiftUI views. | |
struct ContentView: View { | |
var body: some View { | |
CustomParentView { | |
Text("Test") | |
.foregroundColor(.white) | |
} | |
} | |
} | |
let viewController = UIHostingController(rootView: ContentView()) | |
PlaygroundPage.current.liveView = viewController |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment