Unfortunately, SwiftUI cannot detect changes of properties in an Array, when the Element is a reference type.
(Even when you add @State on the Array declaration or you add @Published to the properties.)
So, changes to color or order do not trigger UI updates in ContentViews.
If you make XRectModel struct, and add @State to rects, you will find zIndex works correctly:
struct XRectModel: Hashable {
var id = UUID()
var color: Color
var order: Double
}
struct XRect: View {
static var maxorder: Double = 0
@Binding var rect: XRectModel
@State var pos: CGSize = CGSize()
var drag: some Gesture {
DragGesture()
.onChanged { pos in
self.pos = pos.translation
XRect.maxorder += 1
rect.order = XRect.maxorder
print("Rect: \(rect.color.description), Order: \(rect.order)")
}
}
var body: some View {
Rectangle()
.foregroundColor(rect.color)
.frame(width: 200, height: 200, alignment: .center)
.offset(pos)
.gesture(drag)
}
}
struct ContentViews: View {
@State var rects = [XRectModel(color: Color.green, order: 0),
XRectModel(color: Color.yellow, order: 0),
XRectModel(color: Color.red, order: 0)]
var body: some View {
ZStack {
Color.blue
ForEach(rects.indices, id: \.self) { index in
XRect(rect: $rects[index])
.zIndex(rects[index].order)
}
}
}
}