简体   繁体   中英

SwiftUI - Show custom ViewController from View

I have a Button in my View that call a custom View Controller ( UIViewControllerRepresentable ) because, the external library that I use, needs a view controller as parameter to show its own popups ( and of course I cannot change ).

For this reason I've created this middleware view controller but using this logic, the behaviour is not what i want...
Two popups, one on top of the other will be opened.

This because this library is not created thinking in SwiftUI, but the classic UIKit.


What I've done:

ContentView

struct ContentView: View {
    @State var showViewController = false

    var body: some View {
        VStack(alignment: .leading, content: {
            Button("SHOW VIEW CONTROLLER") {
                showViewController.toggle()
            }
        })
        .sheet(isPresented: $showViewController, content: {
            EmptyViewController()
        })
    }
}

EmptyController:

struct EmptyViewController: UIViewControllerRepresentable {
    func makeUIViewController(context: UIViewControllerRepresentableContext<EmptyViewController>) -> UIViewController {
        let vc = UIViewController()
        vc.view.backgroundColor = .systemRed

        let extLibVC = ExternalLibraryClass()
        extLibVC.doSomethingAndShowVC(from: vc) // issue here, because I need to pass VC
        
        return vc
    }
    
    func updateUIViewController(_ uiViewController: UIViewController, context: UIViewControllerRepresentableContext<EmptyViewController>) {}
}

This is the result in this case:

演示

There is a way to use directly the

let extLibVC = ExternalLibraryClass()
extLibVC.doSomethingAndShowVC(from: vc)

in the View without passing from another view controller and avoid multiple popups?

Basically I don't want to see the RED View controller, but directly the GREEN one.

Just use NavigationLink , this push new page into stack using inside NavigationView

struct test: View {
var body: some View {
    NavigationView{
        NavigationLink(
            destination: EmptyViewController()
                        .navigationBarTitle(Text("Title"), displayMode: .inline),
            label: {
                Text("SHOW VIEW CONTROLLER")
            })
    }
}

}

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