Skip to content

Instantly share code, notes, and snippets.

@drosenstark
Last active April 26, 2023 19:49
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 drosenstark/a4b09abfb7c28a2fba3c9f9c986d5895 to your computer and use it in GitHub Desktop.
Save drosenstark/a4b09abfb7c28a2fba3c9f9c986d5895 to your computer and use it in GitHub Desktop.
UIKit holding SwiftUI Holding UIKit
// (c) Confusion Studios LLC and affiliates. Confidential and proprietary.
import SwiftUI
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
view.backgroundColor = .orange
let swiftUIView = ContentView().asUIView
swiftUIView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(swiftUIView)
NSLayoutConstraint.activate([
swiftUIView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
swiftUIView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
swiftUIView.topAnchor.constraint(equalTo: view.topAnchor),
swiftUIView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
])
}
}
struct ContentView: View {
var body: some View {
VStack {
Text("Hello, world!").padding(.top, 10)
UIViewWrapper(uiView: makeUIView(with: .blue))
HStack {
UIViewWrapper(uiView: makeUIView(with: .blue))
UIViewWrapper(uiView: makeUIView(with: .cyan))
UIViewWrapper(uiView: makeUIView(with: .orange))
}
UIViewWrapper(uiView: makeUIView(with: .green))
HStack {
UIViewWrapper(uiView: makeUIView(with: .blue))
UIViewWrapper(uiView: makeUIView(with: .cyan))
UIViewWrapper(uiView: makeUIView(with: .orange))
}
Text("Hello, world!").padding(.bottom, 10)
}
}
func makeUIView(with color: UIColor) -> UIView {
let view = UIView()
view.backgroundColor = color
return view
}
}
struct UIViewWrapper: UIViewRepresentable {
typealias UIViewType = UIView
let uiView: UIView
func makeUIView(context: Context) -> UIView {
return uiView
}
func updateUIView(_ uiView: UIView, context: Context) {
// Update your UIView if needed
}
}
extension View {
var asUIView: UIView {
let hostingController = UIHostingController(rootView: self)
return hostingController.view
}
}
@drosenstark
Copy link
Author

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment