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

时间:2020-05-21 23:21:07

标签: xcode swiftui instance-variables

因此,在ContentView中,我使用以下内容创建了一个视图:

{
"Templates" : [
    {
        "Name" : "Apple Pie",
        "Manufacturer" : "Burger King",
        "Model" : "Apple",
        "Type" : "Pie",
        "Info" : [
            {
                "Pack Size" : 3,
        "Cost" : 12

            },
            {
                "Pack Size" : 1,
        "Cost" : 5
            }
        ]
    },

    {
        "Name" : "Vanilla Icecream",
        "Manufacturer" : "JP Licks",
        "Model" : "Vanilla",
        "Type" : "Icecream",
        "Info" : [
            {
                "Pack Size" : 2,
        "Cost" : 12
            },
            {
                 "Pack Size" : 3,
         "Cost" : 14
            }
        ]
    },

    {
        "Name" : "Raspberry Cream Cheese",
        "Manufacturer" : "Philadelphia",
        "Model" : "Raspberry",
        "Type" : "Cream cheese",
        "Info" : [
            {
                 "Pack Size" : 4,
         "Cost" : 9
            },
            {
                 "Pack Size" : 2,
         "Cost" : 6
            }

        ]
    }
],

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

ViewName()

但这只是关于如何获取价值的一种猜测;它没有用。任何建议将不胜感激!

2 个答案:

答案 0 :(得分:2)

您可以使用@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
    }
}

答案 1 :(得分:1)

无论出于何种原因,从技术上讲,都可以通过回调关闭来完成。

警告: 此类回调中的操作不应导致刷新发件人视图,否则将只是循环或丢失值

这里是用法和解决方案的演示。使用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 = ""
}