SwiftUI NavigationBar Title using UIHostingController does not Display correctly until NSLayoutConstraint is broken

52 views Asked by At

I'm facing an issue where the navigation bar title of a SwiftUI view does not display correctly on the first render. It only appears correctly after switching to another tab and then coming back. Alongside this issue, I'm receiving the following constraint error in the console:enter image description here

[UIKitCore] Unable to simultaneously satisfy constraints. ... Will attempt to recover by breaking constraint <NSLayoutConstraint:0x600002206260 V:[Overview]-(0)-[UIFocusContainerGuide:0x600003def750'UINavigationControllerContentFocusContainerGuide'] (active, names: Overview:0x112d9aee0 )> ...

struct ContentView: View {

var body: some View {
    NavigationStack {
        ScrollView {
            VStack(spacing: 20) {
                ForEach(0..<10) { index in
                    VStack {
                        Text("Section \(index)").font(.headline).padding()
                        ForEach(0..<5) { itemIndex in
                            Text("Item \(itemIndex)").padding()
                        }
                    }
                    .frame(maxWidth: .infinity)
                    .background(Color.gray.opacity(0.2))
                    .cornerRadius(10)
                    .padding(.horizontal)
                }
            }
        }.navigationTitle("Overview").navigationBarTitleDisplayMode(.automatic)
    }
}

}

class ExpoContentView: ExpoView {
required init(appContext: AppContext? = nil) {
    super.init(appContext: appContext)
    self.backgroundColor = .white
    // Init the view controller
    let contentView = ContentView()
    let hostingController = UIHostingController(rootView: contentView)
    setupHostingController(hostingController)
    func setupHostingController(_ hostingController: UIHostingController<some View>) {
        hostingController.view.translatesAutoresizingMaskIntoConstraints = false
        hostingController.view.backgroundColor = .clear
        addSubview(hostingController.view)
        NSLayoutConstraint.activate([
            hostingController.view.topAnchor.constraint(equalTo: self.topAnchor),
            hostingController.view.bottomAnchor.constraint(equalTo: safeAreaLayoutGuide.bottomAnchor),
            hostingController.view.leadingAnchor.constraint(equalTo: safeAreaLayoutGuide.leadingAnchor),
            hostingController.view.trailingAnchor.constraint(equalTo: safeAreaLayoutGuide.trailingAnchor)
        ])
       
    }
   
}

}

How can I achieve that it is correctly shown at the first render?

0

There are 0 answers