SwiftUI View inside UIView

2.3k views Asked by At

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)
    }

enter image description here

And the result enter image description here

1

There are 1 answers

0
Srivathsa On

Multiple options to try to fix this issue :-)

try layoutIfNeeded after adding hostingcontroller' view to superview

Or

try to set frames inside viewWillLayoutSubviews or override loadView to setup frame

Or

try enabling auto-sizing masks

pointView.autoresizingMask = [.flexibleWidth, .flexibleHeight]

Or

add below constraints

NSLayoutConstraint.activate([
    pointView.centerXAnchor.constraint(equalTo: view.centerXAnchor),
    pointView.centerYAnchor.constraint(equalTo: view.centerYAnchor),
    pointView.heightAnchor.constraint(equalToConstant:380),
    pointView.widthAnchor.constraint(equalToConstant:160)
])