swift - ObservedObject 更改不会重绘 SwiftUI 视图
问题描述
我尝试在 SwiftUI 中构建相当复杂的视图。结构是这样的:
struct ContentView<V: SpaceVertexProtocol>: View where V.Coord.Axis : StyledAxisProtocol{
@EnvironmentObject var environment: ViewsEnvironments<V>
@ObservedObject var global: GlobalEnvironment<V>
var body: some View {
// It will be HStack, for a while just one view
SpaceVerticesView(coordinates: $global.coordinates, vertices: $global.vertices)
.padding(EdgeInsets(top: 5, leading: 5, bottom: 5, trailing: 5))
.environmentObject(environment.spaceVerticesView)
}
}
public struct SpaceVerticesView<V:SpaceVertexProtocol> : View {
...
@Binding var coordinates : [V.Coord]
...
func updateCoordnates {
coordinates = ... // yes, this updates view, they're changed by `coordinates[index].at = something`
}
public var body: some View {
...
SpotsView(coordinates: $coordinates,....)
...
}
struct SpotsView<V:SpaceVertexProtocol> : View {
...
@Binding var coordinates: [V.Coord]
var spots: [SpotView<V>] {
var result: [SpotView<V>] = []
...
//counts and adds views initiated as:
result.append(SpotView(coordinates: $coordinates,...)
...
return result
}
var body: some View {
return ZStack {
// makes some SpotView on top
ForEach(0..<spots.count, id: \.self) { index in
return self.spots[index]
}
}
}
还有两个级别,总是作为变量coordinates
传递。在最深层的视图中, var返回$coordinates
@Binding
body
Shape
var body {
...
return spotShape
.contentShape(spotShape.clickArea).offset(x: 0, y: shift)
.onTapGesture {
print ("Tap gesture:",self)
print (self.coordinates, targetCoordinates)
self.coordinates = targetCoordinates
我可以看到coordinates
已更新,但未重绘视图。如果我点击外部clickArea
,SpaceVerticesView.updateCoordinates(...)
被触发,coordinates
被改变并且视图被重绘。Shape
@Binding
无效吗?为什么没有反应?
什么时候coordinates
是@EnvironmentObject
它的一部分是好的。
解决方案
推荐阅读
- python - 如何在 Tkinter python 中为文本而不是为行添加背景
- c - 获得免费():执行代码时大小无效
- android - RoomDB - 你能加入来自不同数据库的表吗
- javascript - Three.js bloomPass 让整个场景变成 8 位的样子
- swift - Swift LayoutConstraint 在键盘框架更改时中断
- r - 如何从 R 中的 PTAK 包中重新排列 PARAFAC 模型的数组中的数据
- c++ - 使用三元运算符定义向量时出现主表达式错误
- mysql - json 路径中具有特殊字符的 MySQL
- gnuradio - USRP N320 低频段中心频移
- swift - 给定的 json 数据不是有效的 json