Last active
April 26, 2023 19:49
-
-
Save drosenstark/a4b09abfb7c28a2fba3c9f9c986d5895 to your computer and use it in GitHub Desktop.
UIKit holding SwiftUI Holding UIKit
This file contains hidden or 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
// (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 | |
} | |
} |
Author
drosenstark
commented
Apr 26, 2023
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment