在SwiftUI中使用DragGesture()时如何防止位置跳变

时间:2020-07-14 17:11:57

标签: ios swift swiftui

我一直在尝试重新创建许多苹果iOS应用程序中看到的卡片视图。

这是卡片视图

struct CardView<Content: View>: View {
    let content: (DisplayMode) -> Content

    @State var displayMode: DisplayMode = DisplayMode.fullSize
    @State var currentOffset: CGFloat = 25
    
    @Environment(\.colorScheme) var colorScheme
    
    @State var lastOffset: CGFloat = 25

    var body: some View {
        VStack(spacing: 5) {
            Rectangle()
                .fill(colorScheme == .dark ? Color.lightBackground.opacity(0.65) : Color.darkBackground.opacity(0.65))
                .frame(minHeight: 0, maxHeight: 5, alignment: .top)
                .cornerRadius(25)
                .padding([.leading, .trailing], 170)
                .padding(.top, 10)
        
            content(displayMode)
                .padding(.top, 0)
        }
        .frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity, alignment: .top)
        .background(colorScheme == .dark ? Color.darkBackground : Color.lightBackground)
        .cornerRadius(25, corners: [.topLeft, .topRight])
        .edgesIgnoringSafeArea(.bottom)
        .offset(x: 0, y: currentOffset)
        .shadow(color: Color.black.opacity(0.2), radius: 5, x: 0, y: 0)
        .gesture(DragGesture(minimumDistance: 5).onChanged { value in
            currentOffset = value.location.y
        }.onEnded { value in
            displayMode = displayMode(for: value.location.y)
            currentOffset = displayMode.rawValue
        }).animation(.spring(response: 0.55, dampingFraction: 0.825, blendDuration: 0))
    }
    
    private func displayMode(for height: CGFloat) -> DisplayMode {
        if height < 250 {
            return .fullSize
        } else if height < 500 {
            return .thirdSize
        } else {
            return .tabSize
        }
    }
}

如您所见,我在gesture()视图中附加了VStack修饰符。在此过程中,我们提供了一个DragGesture函数,在该函数中,我可以更改视图的偏移量,并且在手势完成将视图移动到预定义位置后即可。

问题在于用户将手指放在视图中间。视图将跳到该位置。如下面的GIF所示。

https://media.giphy.com/media/XCrc9KlJ9VLUQEd2pJ/giphy.gif

有人知道必须解决此问题吗?

谢谢

0 个答案:

没有答案