我正在尝试复制长按按钮效果,例如Apple的默认按钮效果,但是具有自定义样式。
我有一个自定义视图,在这里我称之为onLongPressGesture
。问题是即使我的手指仍在按,pressing
变量也被设置为false。
我只是将手指移到LongPressGesture框架上的视图之外。
当我将手指移到框架区域之外时,我不想将pressing
变量设置为false。
我该如何实现?
这是我的代码:
.onLongPressGesture(minimumDuration: 1000000000, maximumDistance: 100, pressing: {
pressing in
if !pressing {
self.action?()
self.showNextScreen = true
} else {
withAnimation(.spring()) {
self.showGrayBackgound = true
}
}
}) { }
答案 0 :(得分:1)
使用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
将位于屏幕边界之外,长按将保持激活状态,直到释放它为止。但是,使用LongPressGesture
无法在MacOS行为中单击并按住,同时在框架外拖动并向后拖动,以关闭和重新打开按钮的状态。一旦位于maximumDistance
之外,手势就完成了。