【问题标题】:View does not update whet some variables in @state struct changesView 不会更新 @state 结构中的某些变量更改
【发布时间】:2022-06-14 01:02:28
【问题描述】:

我在这里读过类似的问题,但还是不明白。

我有一个结构(我做了一些小改动)

import Foundation
import CoreGraphics

typealias NodeID = UUID

struct Node: Identifiable {
  var id: NodeID = NodeID()
  var NodeWidth: CGFloat = 60.0
  var position: CGPoint = .zero
  var text: String = ""


  var visualID: String {
    return id.uuidString
      + "\(text.hashValue)"
  }
}

我对这个结构的状态有一个看法

import SwiftUI

struct NodeView: View {
  
@State var node: Node
  
  var body: some View {
    Capsule()
      .fill(Color.gray)
      .frame(width: node.NodeWidth, height: 50)
  }
}

拥有将其组装成一体的视图...

import SwiftUI

struct NodeMapView: View {
  @Binding var nodes: [Node]
  var body: some View {
    ZStack {
      ForEach(nodes, id: \.visualID) { node in
        NodeView(node: node)
          .offset(x: node.position.x, y: node.position.y)
          }
      }
    }
  }

并具有多种功能

  func updateNodeText(_ srcNode: Node, string: String) {
    var newNode = srcNode
    newNode.text = string
    replace(srcNode, with: newNode)
  }

  func updateNodeWidth(_ srcNode: Node, string: String) {
    var newNode = srcNode
    if let n = NumberFormatter().number(from: string) {
      newNode.timedist = CGFloat(truncating: n)
    }
    replace(srcNode, with: newNode)
  }
 
  func updatePosX(_ srcNode: Node, string: String) {
    var newNode = srcNode
    if let n = NumberFormatter().number(from: string) {
      newNode.position.x = CGFloat(truncating: n)
    }
    replace(srcNode, with: newNode)
  }

问题是: 当我使用 updateNodeText 或 updatePosX 函数时 - 视图已更改 - 一切正常,但是当我使用 updateNodeWidth 函数时没有任何反应。 参数改变了,我可以在文本字段中看到它,但视图没有。

我做错了什么?

更新:在调试时我发现在 NodeView 结构参数中没有改变(我不知道为什么)但是当我在函数中时参数是正确的。但是当我使用updateNodeText函数时,NodeView中的参数更新正常了。

【问题讨论】:

  • 请显示完整(无效)代码。
  • 请尝试将您的示例变成一个最小的、可重现的示例!
  • 尝试用@State标记MyValposition

标签: macos swiftui state


猜你喜欢
  • 2020-04-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-11
  • 2017-04-07
  • 2021-08-06
  • 2022-01-01
  • 1970-01-01
相关资源
最近更新 更多