Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way open UIKit ViewController from SwiftUI

I am not getting the proper solution, How to open UIKit ViewController(With Navigation Controller) from SwiftUI Button clicked.

like image 931
Mazharul Belal Avatar asked Oct 14 '25 20:10

Mazharul Belal


1 Answers

You can do it by using the UIViewControllerRepresentable protocol which is used to manage your UIKit ViewController in the SwiftUI.

Here is the code to show your ViewController from SwiftUI View interface.

SwiftUI View

struct ContentView: View {

    @State var isOpenView = false

    var body: some View {
    
        NavigationView {

            VStack {

                //show your view controller
                NavigationLink(destination: TestControllerView(), isActive: $isOpenView) {
                    EmptyView()
                }
            
                Button(action: {
                    self.isOpenView = true
                }){
                    Text("Tap Me")
                }                    
            }
        }
    }
}

Now wrap your ViewController into UIViewControllerRepresentable

struct TestControllerView : UIViewControllerRepresentable {

     func updateUIViewController(_ uiViewController: UIViewControllerType, context: Context) {
    
     }

     func makeUIViewController(context: Context) -> some UIViewController {

        guard let viewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(identifier: "TestViewController") as? TestViewController else {
            fatalError("ViewController not implemented in storyboard")
        }
    
        return viewController
     }
}

Here is your ViewController.Swift File code

import UIKit

class TestViewController: UIViewController {

     override func viewDidLoad() {
         super.viewDidLoad()
         // Do any additional setup after loading the view.
     }

     @IBAction func btnBackClicked(_ sender : UIButton) {
         self.dismiss(animated: true, completion: nil)
     }
}
like image 184
Hardik Shekhat Avatar answered Oct 18 '25 02:10

Hardik Shekhat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!