Search code examples
xcodeswiftuiinstance-variables

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


So in ContentView, I've created a view with the following:

ViewName()

I'd like to change a variable in ContentView to the value of a variable in ViewName. I was hoping I could do something like:

ViewName() {
    contentViewVariable = self.variableNameInViewNameInstance
}

but that was just kind of a guess as to how to access the value; it didn't work. Any suggestions would be greatly appreciated!


Solution

  • For whatever reason it is needed technically it is possible to do via callback closure.

    Caution: the action in such callback should not lead to refresh sender view, otherwise it would be just either cycle or value lost

    Here is a demo of usage & solution. Tested with Xcode 11.4 / iOS 13.4

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

    and

    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 = ""
    }