ScrollView 限制 DragGesture 动画

ScrollView limits DragGesture animation

我有 HStack,其中一些图像通过 ForEach 视图显示。每个图像都应用了 DragGesture。我可以在整个屏幕上拖动图像并正确显示动画。但是,当我将带有图像的 HStack 放入 ScrollView 时,当我拖动图像(而不是滚动)时,仅在 ScrollView 区域内显示的 gragging 动画。我怎样才能让它再次显示在整个屏幕中?

import SwiftUI

struct SwiftUIView: View {
    
    @State var position = CGSize.zero
    @GestureState var dragOffset: [CGSize]

        init() {
            let  dragOffsets = [CGSize](repeating: CGSize.zero, count: 36)
            _dragOffset = GestureState(wrappedValue: dragOffsets)
        }
    
    var body: some View {
        ScrollView(.horizontal) {
            HStack(alignment: .center, spacing: 0) {
                ForEach ((0..<player.playersCards.count), id: \.self) { number in
                    Image(player.playersCards[number].pic)
                        .resizable()
                        .frame(width: 93, height: 127)
                        .modifier(CardStyle())
                        .offset(dragOffset[number])

                    .gesture(
                        DragGesture(coordinateSpace: .global)
                            .updating($dragOffset, body: { (value, state, transaction) in

                                state[number] = value.translation

                            })
                    )
                    .animation(.spring())
                }
            }
        }.offset(x: 15, y: 0)
    }
}

您只需要将图像打包到另一个视图(组或 ZStack)中即可!设置这个视图的高度为屏幕的高度,那么图片就会移动到父视图里面:

struct SwiftUIView: View {
    
    private let colors = [Color.blue, Color.yellow, Color.orange, Color.gray, Color.black, Color.green, Color.white]
    
    @State var position = CGSize.zero
    @GestureState var dragOffset: [CGSize]

        init() {
            let  dragOffsets = [CGSize](repeating: CGSize.zero, count: 36)
            _dragOffset = GestureState(wrappedValue: dragOffsets)
        }
    
    var body: some View {
        
        ScrollView(.horizontal) {
            HStack(alignment: .center, spacing: 0) {
                ForEach (Array(0...6), id: \.self) { number in
                    ZStack {
                        Text("\(number.description)")
                            .frame(width: 93, height: 127)
                            .background(colors[number])
                            .offset(dragOffset[number])
                        .gesture(
                            DragGesture(coordinateSpace: .global)
                                .updating($dragOffset, body: { (value, state, transaction) in
                                    state[number] = value.translation

                                })
                        )
                        .animation(.spring())
                    }
                    .frame(width: 93, height: UIScreen.main.bounds.height)
                }
            }
        }
        .background(Color.red)
    }
}