ios – SwiftUI how to manually add a system back button in root view


I have a hybrid app with both UIKit and SwiftUI. The root VC is UINavController in UIKit, and I present UIHostingController to host a SwiftUI feature. The SwiftUI has its own NavigationStack, so I hide the UIKit nav bar in UIHostingController, so that there’s only 1 nav bar:


class MyHostingVC: UIHostingController<AnyView> {
  override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    navigationController?.isNavigationBarHidden = true
  }
  override init(rootView: AnyView) {
    super.init(rootView: rootView)
  }
  required init?(coder aDecoder: NSCoder) {
    fatalError()
  }
}

Now in SwiftUI’s root view, it doesn’t have a back button, because to SwiftUI, it’s the root.

I could easily add a button to top left corner like this:

  @Environment(\.dismiss) var dismiss

    ...


      .toolbar {
        ToolbarItem(placement: .navigationBarLeading) {
          Button("Back") {
            dismiss()
          }
        }
      }

What’s surprisingly good is that dismiss() actually works – it pop’s the whole UIHostingController and returns to my UIKit screens.

I can even add an arrow so it looks like the system back button. However, I would have to do localization for all languages. Is there a better way to force showing the system back button?

Latest articles

spot_imgspot_img

Related articles

Leave a reply

Please enter your comment!
Please enter your name here

spot_imgspot_img