send button action to child swiftui view in uikit view controller in swift

You can pass a @Binding variable to the SwiftUI view from the UIViewController and modify that variable on button action. Here is an example:

In the SwiftUI view:

main.swift
struct ChildView: View {
    @Binding var buttonTapped: Bool
    
    var body: some View {
        Button(action: {
            self.buttonTapped = true
        }) {
            Text("Tap me")
        }
    }
}
212 chars
12 lines

In the UIViewController:

main.swift
struct ContentView: UIViewControllerRepresentable {
    func makeUIViewController(context: Context) -> MyViewController {
        let viewController = MyViewController()
        return viewController
    }
    
    func updateUIViewController(_ uiViewController: MyViewController, context: Context) {
        
    }
}

class MyViewController: UIViewController {
    var buttonTapped: Bool = false

    override func viewDidLoad() {
        super.viewDidLoad()
        
        let childView = ChildView(buttonTapped: $buttonTapped)
        let hostingController = UIHostingController(rootView: childView)
        addChild(hostingController)
        view.addSubview(hostingController.view)
    }
}
697 chars
24 lines

Now the buttonTapped variable in the UIViewController will be modified when the button is tapped in the SwiftUI view.

related categories

gistlibby LogSnag