vikzilla
vikzilla

Reputation: 4138

Handle SwiftUI view callback from UIKit

I have a SwiftUI view showing in a UIViewController. It is rooted in a UIHostingController (which is embedded in a UIContainerView within the view-controller, via storyboard).

Now, this SwiftUI view has a button that I want to handle from inside the UIViewController.

I've tried providing the SwiftUI view a function (named dismiss) like so:

import SwiftUI

struct SkipView: View {
    
    var dismiss: (() -> Void)?

    var body: some View {
        HStack {
            Button(action: {
                let _ = self.dismiss!
            }) {
                Text("Skip")
            }
        }
    }
}

Then in the UIViewController, it looks like this:

@IBSegueAction func addSkipView(_ coder: NSCoder) -> UIViewController? {

    var skipView = SkipView(entry: self.entry)

    skipView.dismiss = {
        self.skipContainerView.isHidden = true
        print("Why isn't this getting called?")
    }

    return UIHostingController(coder: coder, rootView: skipView)
}

However, the skipView.dismiss callback is not getting called in my view-controller.

Any idea as to how I can properly communicate the button action within my SwiftUI view to the UIKit view-controller?

Upvotes: 1

Views: 675

Answers (1)

idz
idz

Reputation: 12988

The code:

let _ = self.dismiss!

does not call self.dismiss; you've no brackets!

You need to do something like this:

if let someDismiss = self.dismiss {
    someDismiss()
}

Upvotes: 1

Related Questions