在 SwiftUI 中使用 ForEach 进行迭代时,如何确保视图出现在其他视图之上?

maf*_*rja 1 swiftui

请注意,向右打开的“胶囊”形状位于绿紫色条下方。我有一个 SwiftUI 视图,它是一个圆形视图,点击时会打开,并且应该延伸到 UI 的右侧。我如何确保它会出现在其他用户界面的顶部?其他 UI 元素是使用 ForEach 循环创建的。我尝试了 zindex 但它不起作用。我缺少什么?

ZStack {
  VStack(alignment: .leading) {
    Text("ALL WORKSTATIONS")
    ZStack {

      ChartBackground()

      HStack(alignment: .bottom, spacing: 15.0) {



        ForEach(Array(zip(1..., dataPoints)), id: \.1.id) { number, point in
          VStack(alignment: .center, spacing: 5) {



          DataCircle().zIndex(10)
          ChartBar(percentage: point.percentage).zIndex(-1)
          Text(point.month)
            .font(.caption)
        }
        .frame(width: 25.0, height: 200.0, alignment: .bottom)
        .animation(.default)
      }
    }
    .offset(x: 30, y: 20)
       }
      .frame(width: 500, height: 300, alignment: .center)
     }
   }
  }
}
Run Code Online (Sandbox Code Playgroud)

Asp*_*eri 5

.zIndex 对一个容器内的视图有效。因此,为了解决您的情况,正如我假设DataCircle在点击时展开的那样,您需要VStack通过引入某种处理选择来增加每次点击的整个栏的 zIndex。

这里是简化复制的demo来展示效果

演示

struct TestBarZIndex: View {
    @State private var selection: Int? = nil
    var body: some View {
        ZStack {
            VStack(alignment: .leading) {
                Text("ALL WORKSTATIONS")
                ZStack {
                    Rectangle().fill(Color.yellow)//ChartBackground()
                    HStack(alignment: .bottom, spacing: 15.0) {
                        ForEach(1...10) { number in
                            VStack(spacing: 5) {
                                Spacer()
                                ZStack() { // DataCircle()
                                    Circle().fill(Color.pink).frame(width: 20, height: 20)
                                        .onTapGesture { self.selection = number }
                                    if number == self.selection {
                                        Text("Top Description").fixedSize()
                                    }
                                }
                                Rectangle().fill(Color.green) // ChartBar()
                                    .frame(width: 20, height: CGFloat(Int.random(in: 40...150)))
                                Text("Jun")
                                    .font(.caption)
                            }.zIndex(number == self.selection ? 1 : 0) // << here !!
                            .frame(width: 25.0, height: 200.0, alignment: .bottom)
                            .animation(.default)
                        }
                    }
                }
                .frame(height: 300)
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)