Home > Software engineering >  Return from SwiftUI to Storyboard with a SwiftUI button
Return from SwiftUI to Storyboard with a SwiftUI button

Time:04-14

In an attempt to merge a SwiftUI view and Storyboard I have created a segue from a storyboard into a SwiftUI view, but currently have no way of getting back.

I don't want to do this through a navigation bar, rather a button in my SwiftUI view which unwinds the segue back to the main.storyboard view.

Storyboard View

The way I have achieved my outcome so far is by using the SwiftUI view as a hosting controller, and then added a segue from the View Controller to the Child Hosting Controller.

The button which I want to unwind the segue looks like this:

Button(action: {
    print("button pressed") // UNWIND SEGUE HERE

  }) {
      Image("TopLeft")
      .renderingMode(.original)
      .resizable()
      .scaledToFit()
      .frame(width: 15, height: 15)
  }
}

This code is linked to a class called SecondView which is the SwiftUI code. SecondView is activated by a subclass ChildHostingController, linked to the UIHostingController on the storyboard:

class ChildHostingController: UIHostingController<SecondView> {

    required init?(coder: NSCoder) {
        super.init(coder: coder,rootView: SecondView());
    }

    override func viewDidLoad() {
        super.viewDidLoad()
    }
}

Is there any possible way to unwind the segue back to View Controller?

Much appreciated!!

CodePudding user response:

A possible approach is to inject a closure with unwind action from a view controller via view model into SwiftUI view and call it inside SwiftUI view button.

Here is main part:

super.init(coder: coder, rootView: SecondView(vm: viewModel))
viewModel.unwind = { [weak self] in
   // call unwind segue created in storyboard
    self?.performSegue(withIdentifier: "unwind_segue_identifier", sender: self)
}

Complete findings and code here

  • Related