【问题标题】:Swift Combine and SwiftUI understanding needs correctionsSwift Combine 和 SwiftUI 理解需要修正
【发布时间】:2020-09-03 12:44:51
【问题描述】:

我尝试做一些简单的事情。在 AppDelegate 中,我需要 var vertices: [SCNVector3] = []。在@IBAction func getVertices(_ sender: Any) 中,我可以读取文件并将新值分配给vertices。简单而有效。但是当我尝试将值传递给 SwiftUI View 时,我遇到了问题。 如果我定义

@State var vertices: [SCNVector3] = []

func applicationDidFinishLaunching(_ aNotification: Notification) {
    ....
    let contentView = CloudView(data: $vertices)
    ....
    window.contentView = NSHostingView(rootView: contentView)
    ...
}

@IBAction func getVertices(_ sender: Any) {
    ...
    do {
        let readVertices: [SCNVector3] = try... // read file and convert to [SCNVector3]
        vertcices = readVertices // assign or not to assign, this is a question
        print (readVertices.count, vertices.count)
    }
    ...
}

然后打印出来:

3500 0

所以,它永远不会更新 CloudViewvertices 始终是一个空数组。

谁能解释一下我应该如何以正确的方式做到这一点?

【问题讨论】:

    标签: swift swiftui combine


    【解决方案1】:

    您不能在 SwiftUI 视图上下文之外使用 @State。在这种情况下,最合适的是使用ObservableObject,例如

    class VerticesStorage: ObservableObject {
       @Published var vertices: [SCNVector3] = []
    }
    

    然后在 AppDelegate 中

    let verticesStorage = VerticesStorage()   // initialize property
    
    func applicationDidFinishLaunching(_ aNotification: Notification) {
        ....
        let contentView = CloudView(data: verticesStorage) // inject reference
        ....
        window.contentView = NSHostingView(rootView: contentView)
        ...
    }
    
    @IBAction func getVertices(_ sender: Any) {
        ...
        do {
            let readVertices: [SCNVector3] = try... // read file and convert to [SCNVector3]
    
            verticesStorage.vertcices = readVertices // update here !!
    
            print (readVertices.count, vertices.count)
        }
        ...
    }
    

    现在在 SwiftUI 部分

    struct CloudView: View {
       @ObservedObject var data: VerticesStorage     // observable !!
    
       var body: some View {
         // present here
       }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-10-15
      • 1970-01-01
      • 1970-01-01
      • 2022-12-31
      • 2021-04-29
      • 2021-01-16
      • 2020-03-23
      • 2021-06-16
      • 2011-10-01
      相关资源
      最近更新 更多