Reputation: 415
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?
Upvotes: 3
Views: 1541
Reputation: 258413
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)
}
Upvotes: 5