【问题标题】:How can I make a view wrapped in a `State` property update with SwiftUI如何使用 SwiftUI 将视图包装在“状态”属性更新中
【发布时间】:2020-06-17 22:30:27
【问题描述】:

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

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

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

【问题讨论】:

  • 在这种情况下,将@Binding 用于countNested 属性是正确的方法。

标签: swiftui swiftui-state


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-29
    • 1970-01-01
    • 2021-10-19
    • 1970-01-01
    • 2022-10-22
    • 2020-03-08
    • 1970-01-01
    • 2021-02-05
    相关资源
    最近更新 更多