Skip to content

Instantly share code, notes, and snippets.

@pitt500
Created January 25, 2023 16:31
Show Gist options
  • Save pitt500/588962af10df237a04665af5033ebfde to your computer and use it in GitHub Desktop.
Save pitt500/588962af10df237a04665af5033ebfde to your computer and use it in GitHub Desktop.
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