首页 > 解决方案 > onLongPressGesture frame in SwiftUI

问题描述

I am trying to replicate a long press button effect like the Apple default one, but with a custom style.

I have a custom view where I call onLongPressGesture. The issue is that the pressing variable is getting set to false even though my finger is still pressing.

I just move my finger outside the the views onLongPressGesture frame.

I want the pressing variable to not get set to false when I move my finger outside the frame area.

How can i achieve that?

Here's my code:


.onLongPressGesture(minimumDuration: 1000000000, maximumDistance: 100, pressing: {
    pressing in
    if !pressing {
        self.action?()
        self.showNextScreen = true
    } else {
        withAnimation(.spring()) {
            self.showGrayBackgound = true
        }
    }
}) { }

标签: swiftswiftui

解决方案


使用maximumDistance参数设置手势应用到视图之外的距离:

struct LongPressView: View {
    @State var isPressing = false
    let action: ()->()

    var body: some View {
        Rectangle()
            .fill(isPressing ? Color.orange : .gray)
            .frame(width: 50, height: 30)
            .onLongPressGesture(minimumDuration: 1000000, maximumDistance: 1000, pressing: { pressing in
                self.isPressing = pressing
                if !pressing { self.action() }
            }, perform: {})
    }
}

足够大maximumDistance的将在屏幕边界之外,并且长按将保持激活状态,直到它被释放。但是,macOS 行为中,您在框架外拖动并返回时单击并按住以使按钮的状态关闭并重新打开,这对于LongPressGesture. 一旦超出maximumDistance,手势就完成了。


推荐阅读