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

标签 swift swiftui uikit combine

我的数据模型属性在我的 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/

相关文章:

ios - SwiftUI:列表上的渐变背景

ios - 在 UIView.animate block 中多次设置不透明度会导致意外的初始动画条件

ios - Objective-C指针和swift

swift - 在 Swift 中,创建符合协议(protocol)要求的对象类型(例如类)时,是否不必使用 getter 和 setter?

SwiftUI TextField 可触摸区域

swift - 为什么我的 SwiftUI 列表再次追加所有对象而不是更新现有对象?

ios - 这个 UIBarButton 是否默认存在于 iOS 中?怎么称呼

ios - 日期选择器看起来像文本字段的输入一样被压扁

ios - 查询后写入 Parse 列 - Swift

swift 3 : issue with AVVideoCompositionCoreAnimationTool to add watermark on video