如何在 ZStack 中正确布局(我有可见性问题)?

How to layout properly in ZStack (I have visibility problem)?

下面是可重现的小代码;

正如您在 运行 演示代码中看到的那样,Element 视图在拖动时确实停留在 Color.blue 下面,尽管它根据 ZStack 在上面。顺便说一句,我也玩过 zIndex 修饰符,但仍然没有运气。您提供任何解决方案吗?谢谢大家

struct ContentView: View {
    
    var body: some View {
        GeometryReader { gr in
            
            ZStack {
            
                Color.blue.opacity(0.3)
                    .aspectRatio(1, contentMode: .fit)
                    .frame(width: gr.size.width)
                
                VStack {
                    Spacer()
                    ScrollView(.horizontal) {
                        HStack {
                            ForEach(1...15, id: \.self) { (idx) in
                                Element(index: idx)
                            }
                        }
                        .padding()
                    }
                    .background(Color.secondary.opacity(0.3))
                }
                
            }
        }
    }
    
}

struct Element: View {
    
    @State private var dragAmount = CGSize.zero
    
    var index: Int
    
    var body: some View {
        Rectangle()
            .frame(width: 80, height: 80)
            .overlay(Text("\(index)").bold().foregroundColor(.white))
            .offset(dragAmount)
            .gesture(
                DragGesture(coordinateSpace: .global)
                    .onChanged {
                        self.dragAmount = CGSize(width: [=10=].translation.width, height: [=10=].translation.height)
                    }
                    .onEnded { _ in
                        self.dragAmount = .zero
                    }
            )
    }
}

How can achieve my goal then, like dragging Element on different view (in this scenario Color.blue)

实际上我们需要通过 ScrollView.

禁用裁剪

下面是基于我的其他答案的辅助扩展的可能方法 ( and )

VStack {
    Spacer()
    ScrollView(.horizontal) {
        HStack {
            ForEach(1...15, id: \.self) { (idx) in
                Element(index: idx)
            }
        }
        .padding()
        .background(ScrollViewConfigurator {
          [=10=]?.clipsToBounds = false              // << here !!
        })

        
    }
    .background(Color.secondary.opacity(0.3))
}