Home > AI > IOS > SwiftUI >

UIViewControllerRepresentable

It is to wrap a UIViewController into a SwiftUI view.

import SwiftUI

struct ContentView: View {
    var body: some View {
        NavigationView {
            NavigationLink(
                destination: SampleView(),
                label: {
                    /*@START_MENU_TOKEN@*/Text("Navigate")/*@END_MENU_TOKEN@*/
                })
                .navigationBarTitle("")
                .navigationBarHidden(true)
        }
    }
}

struct SampleView: View {
    var body: some View {
        SampleViewController()
            .navigationBarTitle("", displayMode: .inline)
    }
}

struct SampleViewController: UIViewControllerRepresentable {
    typealias UIViewControllerType = UIViewController

    func makeUIViewController(context: Context) -> UIViewController {
        let vc = UIViewController()

        let a = UILabel(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height))
        a.backgroundColor = UIColor.orange
        a.text = "If you can see me, that would be great!"
        vc.view.addSubview(a)

        return vc
    }

    func updateUIViewController(_ uiViewController: UIViewController, context: Context) {

    }

}

Leave a Reply