I am trying to inject a SwiftUI view inside of a UIView, and it is showing my SwiftUI view but the frame is way off and I cannot figure out why.
UPDATE: After dismissing the view controller and reloading it again, the SwiftUI view is loaded/presented perfectly, why is that?
This is my SwiftUI View:
@available(iOS 14.0, *)
struct AvailablePointsSummary: View {
@State private var points: PointsResponse? = nil
var body: some View {
if let points = points {
GroupBox(
label: SummaryLabelView(labelText: "Available Points")
) {
SummaryRow(title: "Cash Points", amount: Float(points.cashoutPoints).withCommas())
SummaryRow(title: "Promo Points", amount: Float(points.availablePromoPoints ?? 0).withCommas())
}
.frame(width: 380, height: 160)
} else {
Text("Loading...")
.onAppear {
getPoints()
}
}
}
func getPoints() {
PointsService().getPointsResponse { points in
DispatchQueue.main.async {
self.points = points
}
}
}
}
@available(iOS 14.0, *)
var availPointsSummary = UIHostingController(rootView: AvailablePointsSummary())
Setup in my UIViewController
func setupAvailablePoints(){
let pointView = availPointsSummary.view
pointView?.translatesAutoresizingMaskIntoConstraints = false
pointView?.frame = CGRect(x: 0, y: 0, width: 380, height: 160)
self.availPointsView.addSubview(pointView!)
self.addChild(availPointsSummary)
}
Multiple options to try to fix this issue :-)
try
layoutIfNeeded
after adding hostingcontroller' view to superviewOr
try to set frames inside
viewWillLayoutSubviews
or override loadView to setup frameOr
try enabling auto-sizing masks
Or
add below constraints