首页 > 解决方案 > 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@BindingbodyShape

    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已更新,但未重绘视图。如果我点击外部clickAreaSpaceVerticesView.updateCoordinates(...)被触发,coordinates被改变并且视图被重绘。Shape @Binding无效吗?为什么没有反应?

什么时候coordinates@EnvironmentObject它的一部分是好的。

标签: swiftswiftui

解决方案


推荐阅读