Changing @State variable does not update the View in SwiftUI

Okay, answer is pretty dumb.

There is no need to create func-s. All I have to do is not mark the properties as private but give them an initial value, so they're gonna become optional in the constructor. So user can either specify them, or not care. Like this:

var showXLabels: Bool = false

This way the constructor is either Chart(xLabels:yLabels) or Chart(xLabels:yLabels:showXLabels).

Question had nothing to do with @State.


As in the comments mentioned, @Binding is the way to go.

Here is a minimal example that shows the concept with your code:

struct Chart : View {
    var xValues: [String]
    var yValues: [Double]
    @Binding var showXValues: Bool

    var body: some View {
        if self.showXValues {
            return Text("Showing X Values")
        } else {
            return Text("Hiding X Values")
        }
    }
}

struct ContentView: View {
    @State var showXValues: Bool = false

    var body: some View {
        VStack {
            Chart(xValues: ["a", "b", "c"], yValues: [1, 2, 3], showXValues: self.$showXValues)
            Button(action: {
                self.showXValues.toggle()
            }, label: {
                if self.showXValues {
                    Text("Hide X Values")
                }else {
                    Text("Show X Values")
                }
            })
        }
    }
}

Tags:

Ios

Swift

Swiftui