1

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

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)
    }
}
4

1 回答 1

3

您只需要将图像打包到另一个视图(组或 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)
    }
}

结果

于 2021-09-28T15:11:27.410 回答