简体   繁体   中英

How to call a UIViewController from SwiftUI

I have a SwiftUI TabView, with the 2nd tab item needing to show a UIViewController. How can I embed the UIViewController in this second tab?

class MyUIVC: UIViewController {.....}

The following is some pseudocode to what I want:

struct myTabView: View {
@State var selectedTab: Int = 0
var body: some View {
    mySwiftUIView
      .tabItem { Text("First Tab") }
      .tag(0)

    MyUIVC //This is what I want to do with my UIViewController
      .tabItem { Text("Second Tab") }
      .tag(1)
 }
 }

You need to bridge the ViewController using UIViewControllerRepresentable. . Apple provides documentation on how to use that here:

https://developer.apple.com/documentation/swiftui/uiviewcontrollerrepresentable

Additionally, there's a working example of it within their SwiftUI lessons, most notably the lesson titled "Interfacing with UIKit" which can be found here:

https://developer.apple.com/tutorials/swiftui/interfacing-with-uikit

The example ViewController that they're working with looks like this:


struct PageViewController: UIViewControllerRepresentable {
    var controllers: [UIViewController]

    func makeUIViewController(context: Context) -> UIPageViewController {
        let pageViewController = UIPageViewController(
            transitionStyle: .scroll,
            navigationOrientation: .horizontal)

        return pageViewController
    }

    func updateUIViewController(_ pageViewController: UIPageViewController, context: Context) {
        pageViewController.setViewControllers(
            [controllers[0]], direction: .forward, animated: true)
    }

    class Coordinator: NSObject {
        var parent: PageViewController

        init(_ pageViewController: PageViewController) {
            self.parent = pageViewController
        }
    }
}

That being said, the heart and soul of bridging a ViewController is:

1) Create a struct with a unique name for the ViewController that inherits from UIViewControllerRepresentable

2) Implement the function makeUIViewController(context: Context) with a return type of the UIViewController

3) Implement the function updateUIViewController(_ uiViewController: YourUIViewController, context: Context) without a return

4) As needed, implement a Coordinator class that inherits from NSObject as well as any delegate protocols you need.

There is a bit more depending on what you need that ViewController to do, but this should get you pointed in the right direction.

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