The following is a simplified project to highlight the problem, which I have in a real project.
I have a project, where I add a SwiftUI view with UIHostingController, and the status bar at the top is transparent. I see it when I scroll the SwiftUI view.
It is easy to recreate, create a new iOS project with storyboard, and embed the ViewController
in the storyboard with a NavigationView.
Then replace the ViewController
content with this:
import UIKit
import SwiftUI
final class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let hostingController = UIHostingController(rootView: ScrollView { MySwiftUIView() })
self.addChild(hostingController)
view.addSubview(hostingController.view)
hostingController.view.translatesAutoresizingMaskIntoConstraints = false
hostingController.view.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
hostingController.view.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
hostingController.view.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
hostingController.view.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
self.navigationController?.navigationBar.shadowImage = UIImage()
self.navigationController?.navigationBar.backgroundColor = UIColor.yellow
self.title = "MyTitle"
}
}
struct MySwiftUIView: View {
var body: some View {
ZStack {
Color.green
ScrollView {
VStack {
ForEach(0...100, id: \.self) { index in
Text("This is line \(index)")
}
}
}
}
}
}
The status bar is transparent, and shows the white background of the view:
And when I start scrolling the MySwiftUIView
, it is even more apparent that the status bar is transparent:
I have searched around to find a solution to this, because I want the status bar to have the same color as the navigation bar, and not showing content from the SwiftUI view in the status bar. But so far I haven't found a solution.
CodePudding user response:
Try changing:
hostingController.view.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
to
hostingController.view.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor).isActive = true
I'm not