gpt4 book ai didi

swift - 你如何在 UIKit View Controller 和它呈现的 SwiftUI View 之间共享数据模型?

转载 作者:行者123 更新时间:2023-12-03 09:29:30 24 4
gpt4 key购买 nike

我的数据模型属性在我的 TableView Controller 中声明,并且 SwiftUI View 以模态方式呈现。我想要提供的 Form输入来操作数据模型。我在数据流上找到的资源只是在 SwiftUI View 之间,而我在 UIKit 集成上找到的资源是将 UIKit 嵌入到 SwiftUI 中,而不是相反。
此外,对于值类型(在我的情况下为结构)数据模型是否有一种好的方法,或者是否值得将其重新建模为一个类以使其成为引用类型?

最佳答案

我们来分析...

My data model property is declared in my table view controller and the SwiftUI view is modally presented.


所以这就是你现在所拥有的(可能是简化的)
struct DataModel {
var value: String
}

class ViewController: UIViewController {
var dataModel: DataModel

// ... some other code

func showForm() {
let formView = FormView()
let controller = UIHostingController(rootView: formView)
self.present(controller, animating: true)
}
}

I'd like the presented Form input to manipulate the data model.


这里是上面的更新,其中包含将值类型数据传递到 SwiftUI View 的简单演示,并在无需对 UIKit 部分进行任何重构的情况下将其更新/修改/处理。
这个想法很简单——你将当前模型按值传递给 SwiftUI,然后在完成回调中将其返回并更新并应用于本地属性(因此,如果设置了任何观察者,它们都会按预期工作)
使用 Xcode 12/iOS 14 测试。
class ViewController: UIViewController {
var dataModel: DataModel

// ... some other code

func showForm() {
let formView = FormView(data: self.dataModel) { [weak self] newData in
self?.dismiss(animated: true) {
self?.dataModel = newData
}
}

let controller = UIHostingController(rootView: formView)
self.present(controller, animated: true)
}
}

struct FormView: View {
@State private var data: DataModel
private var completion: (DataModel) -> Void

init(data: DataModel, completion: @escaping (DataModel) -> Void) {
self._data = State(initialValue: data)
self.completion = completion
}

var body: some View {
Form {
TextField("", text: $data.value)
Button("Done") {
completion(data)
}
}
}
}
backup

关于swift - 你如何在 UIKit View Controller 和它呈现的 SwiftUI View 之间共享数据模型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63793261/

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