gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 18:35:09 25 4
gpt4 key购买 nike

如何在回调的闭包中将数据从 SwiftUI View 发送到 UIKit ViewController?假设我们有 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()
}
}

还有 ViewController,其中我们有 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)
}

}
}

如何通过闭包向 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)
}

关于ios - 将数据从 SwiftUI 传递到 UIKit 的回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68894863/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com