简体   繁体   中英

Callback with passing data from SwiftUI to UIKit

How can I send data from SwiftUI view to UIKit ViewController in callback's closure? Let's say we have SwiftUI View:

import SwiftUI

struct MyView: View {
    var buttonPressed: (() -> Void)?
    @State var someData = ""
    
    var body: some View {
        ZStack {
            Color.purple
            Button(action: {
                someData = "new Data"
                self.buttonPressed?()
                
            }) {
                Text("Button")
            }
        }
    }
}

struct MyView_Previews: PreviewProvider {
    static var previews: some View {
        MyView()
    }
}

And ViewController where, inside which we have SwiftUI view:

import UIKit
import SwiftUI

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        
        let swiftUIView = MyView()
        let hostingViewController = UIHostingController(rootView: swiftUIView)
        self.view.addSubview(hostingViewController.view)
        
        hostingViewController.view.translatesAutoresizingMaskIntoConstraints = false
        hostingViewController.view.topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true
        hostingViewController.view.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true
        hostingViewController.view.leftAnchor.constraint(equalTo: self.view.leftAnchor).isActive = true
        hostingViewController.view.rightAnchor.constraint(equalTo: self.view.rightAnchor).isActive = true
        
        hostingViewController.rootView.buttonPressed = {
            print ("callback recived")
            // i know i can try to get the data in this way, but if MyView become too complex than it won't look well
            //print(hostingViewController.rootView.$someData)
        }

    }
}

How can I send someData via closure to ViewController?

You can pass it via argument, like

struct MyView: View {
    var buttonPressed: ((String) -> Void)? // << here !!
    @State var someData = ""
    
    var body: some View {
        ZStack {
            Color.purple
            Button(action: {
                someData = "new Data"
                self.buttonPressed?(someData)  // << here !!

and

    hostingViewController.rootView.buttonPressed = { value in // << here !!
        print("callback received")
        print(value)
    }

backup

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