将数据从 SwiftUI 传递到 UIKit 的回调

Callback with passing data from SwiftUI to UIKit

如何在回调的闭包中将数据从 SwiftUI 视图发送到 UIKit ViewController? 假设我们有 SwiftUI 视图:

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()
    }
}

和ViewController 其中,我们有 SwiftUI 视图:

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)
        }

    }
}

如何通过闭包将 someData 发送到 ViewController?

你可以通过参数传递它,比如

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 !!

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