0

The code below creates a simple HStack that ends up looking like this: preview

The problem is that hitting "increment" increments "Count" but not "Nested". Does anyone know why this is the case and possibly how to fix this? Or do SwiftUI views just fundamentally break when they are nested in a State variable?

struct ContentView: View {
  var body: some View {
    VStack {
      Text("Count: \(count)")
      nested
      Button(action: {
        self.count += 1
        self.nested.count += 1
      }) { Text("Increment") }
    }
  }
  @State var count = 0

  struct Nested: View {
    var body: some View {
      Text("Nested: \(count)")
    }
    @State var count = 0
  }
  @State var nested = Nested()
}

1 Answers1

0

SwiftUI was designed to "nest" views, but you're not using it as intended. State variables are for data owned by the view, and a nested view isn't (or at least, not typically) meant to be a data owned by the view, so it need not be a state variable.

Instead, you can just the count variable as a parameter to the Nested view, and any time the count state variable changes in the parent, its body will be re-rendered:

struct ContentView: View {
  var body: some View {
    VStack {
      Text("Count: \(count)")

      Nested(count: count) // pass the count as an init param

      Button(action: {
        self.count += 1
        self.nested.count += 1
      }) { Text("Increment") }
    }
  }

  @State var count = 0

  struct Nested: View {
    var body: some View {
      Text("Nested: \(count)")
    }
    var count: Int
  }
}
New Dev
  • 48,427
  • 12
  • 87
  • 129