Home > Enterprise >  How to update a property in a separate class from a child view and have the parent view update
How to update a property in a separate class from a child view and have the parent view update

Time:10-13

I'm using Xcode 12 and SwiftUI code and lifecycle.

I Couldn't find an answer to this when I searched here or on google but Im new to code and I may not really know what terms to search for. This is also my first post, I hope I'm doing it right.

I've tried to create a simplified version of what I'm trying to accomplish.

basically the goal is to have the text above the button in the ContentView change from "Title" to "Hello" when I press the button. I know I can achieve this much more simply by placing the title variable in the ContentView struct, but for my purposes I really need it in a separate class.

Thanks in advance.

class Data: ObservableObject {
    @Published var title = "Title"
}

struct ContentView: View {
    @StateObject var data = Data()
    var body: some View {
        VStack {
            Text(data.title)
                .padding()
            ButtonView(data: $data.title) // I'm not sure if this line alone is the problem or if my thinking and code structuring is just all wrong.
        }
    }
}

struct ButtonView: View {
    @Binding var data: Data
    var body: some View {
        
        VStack {
            Button(action: {
                data.title = "Hello"
            }, label: {
                Text("Button")
            })
        }
    }
}

CodePudding user response:

do not use Data as it is already a standard swift name. Then try the following:

class Datax: ObservableObject {
    @Published var title = "Title"
}

struct ContentView: View {
    @StateObject var data = Datax()
    var body: some View {
        VStack {
            Text(data.title).padding()
            ButtonView(data: data)  // <-- here
        }
    }
}

struct ButtonView: View {
    @ObservedObject var data: Datax  // <-- here
    
    var body: some View {
        VStack {
            Button(action: {
                data.title = "Hello"
            }, label: {
                Text("Button")
            })
        }
    }
}
  • Related