GarySabo
GarySabo

Reputation: 6710

How to push to a UIKit ViewController with back button from a SwiftUI View

I've added a SwiftUI View to an existing UIKit/Storyboard project. The SwiftUI View is embedded in a UIHostingController. However, I now want to push to an existing UIViewController so that I have a back button and navigation bar. The code below obviously just presents the UIViewController modally, how can I do this?

class DashBoardHostingController: UIHostingController<DashboardView> {
    required init?(coder: NSCoder) {
        super.init(coder: coder, rootView: DashboardView())
    }
}

struct DashboardView: View {
    
    var body: some View {
            ScrollView {
                VStack(alignment: .leading) {

 HStack {
                        Text("Workouts")
                            .font(.title)
                            .fontWeight(.bold)
                            .padding(.leading)
                        Spacer()
                        
                        Button(action: {
                            let storyBoard: UIStoryboard =  UIStoryboard(name: "Version3", bundle: nil)
                            let subscribeViewController = storyBoard.instantiateViewController(withIdentifier: "skateListVC") as! SkateListTableViewController
                            UIApplication.topViewController()?.present(subscribeViewController, animated: true, completion: nil)
                        }) {
                            Text("Show More")
                        }
                        .padding(.trailing)
                    }
                    ZStack {
                        VStack(alignment: .leading) {
                            WorkoutListView(workouts: [MockWorkout().getMockWorkout()])
                        }
                        .frame(maxWidth: .infinity, alignment: .leading)
                        .padding(20)
                        .background(Color.white)
                        .cornerRadius(10)
                        .padding()
                        }
}
}

Upvotes: 1

Views: 3023

Answers (1)

Paul
Paul

Reputation: 46

Without going and trying this myself, I would think that your SwiftUI view needs to be within a navigationView so that there is a navigation controller to be pushed onto. If UIHostingController provides a navigation controller on its own then you should be able to just change UIApplication.topViewController()?.present(subscribeViewController, animated: true, completion: nil) to UIApplication.topViewController()?.navigationController.pushViewController(subscribeViewController, animated: true)

Either way, you will need to make sure that there is a navigation controller which can be pushed onto.

I think the better way to do this actually would be to wrap the old UIKit vc in a UIViewControllerRepresentable and it can be treated like a normal swiftui view. A great tutorial can be found here Interfacing with UIKit

Upvotes: 3

Related Questions