将数据从 SwiftUI 传递到 UIKit 的回调
Posted
技术标签:
【中文标题】将数据从 SwiftUI 传递到 UIKit 的回调【英文标题】:Callback with passing data from SwiftUI to UIKit 【发布时间】:2021-08-23 15:02:35 【问题描述】:如何在回调的闭包中将数据从 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)
如何通过闭包向 ViewController 发送 someData?
【问题讨论】:
只是让它非可选,这将生成初始化器,您可以将所需的逻辑传递给它 【参考方案1】:你可以通过参数传递它,比如
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)
【讨论】:
谢谢!正是我想要实现的方式,但是闭包语法有问题。以上是关于将数据从 SwiftUI 传递到 UIKit 的回调的主要内容,如果未能解决你的问题,请参考以下文章
将自定义 UIKit 事件从自定义 UIKit 控件公开到 SwiftUI
SwiftUI – 将数据从 SwiftUIView 传递到 SceneKit