1

下面是可重现的小代码;

正如您在运行演示代码时所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: $0.translation.width, height: $0.translation.height)
                    }
                    .onEnded { _ in
                        self.dragAmount = .zero
                    }
            )
    }
}

4

1 回答 1

2

那么如何实现我的目标,比如在不同的视图上拖动元素(在这种情况下 Color.blue)

实际上我们需要禁用剪切ScrollView

以下是基于我的其他答案(https://stackoverflow.com/a/63322713/12299030https://stackoverflow.com/a/60855853/12299030)的帮助扩展的可能方法

演示

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

        
    }
    .background(Color.secondary.opacity(0.3))
}
于 2020-12-02T18:41:51.487 回答