Created
January 25, 2023 16:31
-
-
Save pitt500/588962af10df237a04665af5033ebfde 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
import UIKit | |
// 1. Import SwiftUI | |
import SwiftUI | |
class ViewController: UIViewController { | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
// 2. Initialize SwiftUI View | |
let image = Image( | |
systemName: "star.fill" | |
) | |
.resizable() | |
.foregroundColor(.red) | |
// 3. Create a UIHostingController to wrap SwiftUI view | |
let hostingController = UIHostingController( | |
rootView: image | |
) | |
// 4. Add hosting to Parent View and ViewController | |
self.addChild(hostingController) | |
self.view.addSubview(hostingController.view) | |
hostingController.didMove(toParent: self) | |
// 5. Position and size | |
let swiftuiView = hostingController.view! | |
swiftuiView.translatesAutoresizingMaskIntoConstraints = false | |
let horizontalConstraint = swiftuiView.centerXAnchor.constraint(equalTo: view.centerXAnchor) | |
let verticalConstraint = swiftuiView.centerYAnchor.constraint(equalTo: view.centerYAnchor) | |
let widthConstraint = swiftuiView.widthAnchor.constraint(equalToConstant: 200) | |
let heightConstraint = swiftuiView.heightAnchor.constraint(equalToConstant: 200) | |
view.addConstraints([ | |
horizontalConstraint, | |
verticalConstraint, | |
widthConstraint, | |
heightConstraint | |
]) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment