首页 > 解决方案 > 如何使用 SwiftUI 将视图包装在“状态”属性更新中

问题描述

下面的代码创建了一个简单的代码HStack,最终看起来像这样: 预习

问题是点击“增量”会增加“计数”而不是“嵌套”。有谁知道为什么会这样,以及如何解决这个问题?State或者当 SwiftUI 视图嵌套在变量中时,它们是否会从根本上中断?

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()
}

标签: swiftuiswiftui-state

解决方案


SwiftUI 旨在“嵌套”视图,但您并没有按预期使用它。状态变量用于视图拥有的数据,嵌套视图不(或至少,通常不)意味着视图拥有的数据,因此它不必是状态变量。

相反,您可以只将count变量作为Nested视图的参数,并且任何时候count父级中的状态变量发生变化,其主体都会重新渲染:

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

推荐阅读