如何在 ContentView SwiftUI 中访问视图实例的变量?

How to access a variable of an instance of a view in ContentView SwiftUI?

所以在 ContentView 中,我创建了一个包含以下内容的视图:

ViewName()

我想将 ContentView 中的变量更改为 ViewName 中变量的值。我希望我可以做类似的事情:

ViewName() {
    contentViewVariable = self.variableNameInViewNameInstance
}

但这只是关于如何访问该值的一种猜测;它没有用。如有任何建议,我们将不胜感激!

您可以使用 @State@Binding 来实现。您应该在 2019 年观看这些 WWDC 视频以了解更多相关信息。

  • wwdc 2019 204-swiftui简介
  • wwdc 2019 216 - swiftui 精要
  • wwdc 2019 226 - 数据流经swiftui
struct ContentView: View {
    @State private var variable: String

    var body: some View {
        ViewName($variable)
    }
}

struct ViewName: View {
    @Binding var variableInViewName: String

    init(variable: Binding<String>) {
        _variableInViewName = variable
    }

    doSomething() {
        // updates variableInViewName and also variable in ContentView
        self.variableInViewName = newValue
    }
}

无论出于何种原因,技术上需要它,都可以通过回调闭包来完成。

注意: 此类回调中的操作不应导致刷新发送方视图,否则将只是循环或丢失值

这是一个使用和解决方案的演示。使用 Xcode 11.4 / iOS 13.4

测试
ViewName { sender in
    print("Use value: \(sender.vm.text)")
}

struct ViewName: View {

    @ObservedObject var vm = ViewNameViewModel()

    var callback: ((ViewName) -> Void)? = nil    // << declare

    var body: some View {
        HStack {
            TextField("Enter:", text: $vm.text)
        }.onReceive(vm.$text) { _ in
            if let callback = self.callback {
                callback(self)       // << demo of usage
            }
        }
    }
}

class ViewNameViewModel: ObservableObject {
    @Published var text: String = ""
}