0

I have a SwiftUI View wrapped in a UIHostingController that's then pushed onto the nav stack from a UIViewController.

It's pushed in this way:

let controller = TransactionDetailsHostingController(transactionRecord: record)
navigationController?.pushViewController(controller, animated: true)

I want a custom back button that will pop the view from the navstack and I tried the technique used here and elsewhere: SwiftUI - Is there a popViewController equivalent in SwiftUI?

Unfortunately, it doesn't work. The wrapped view doesn't pop from the navstack. I need a solution that works on iOS 13.

Aaron Bratcher
  • 6,051
  • 2
  • 39
  • 70

1 Answers1

0

There are two approaches for pop to view the controller.

  1. Use closure. Create closure inside the SwiftUI view and call from the controller. Here is the demo.
struct SwiftUIView: View {
    var onBack: () -> Void
    
    var body: some View {
        Button(action: {
            onBack()
        }, label: {
            Text("Go to back")
        })
    }
}

class ViewController: UIViewController {
    
    @IBAction func onNavigation(_ sender: UIButton) {
        let controller = UIHostingController(rootView: SwiftUIView(onBack: {
            self.navigationController?.popViewController(animated: true)
        }))
        navigationController?.pushViewController(controller, animated: true)
    }
}


  1. Find the top most controller and pop. You can find top controller from here

And then use like this

UIApplication.shared.topMostViewController()?.navigationController?.popViewController(animated: true)
Raja Kishan
  • 16,767
  • 2
  • 26
  • 52