简体   繁体   中英

Return from SwiftUI to Storyboard with a SwiftUI button

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.

故事板视图

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!!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM