swift - 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
}
}
}) { }
解决方案
使用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
,手势就完成了。
推荐阅读
- tfs - 发布分支可以用于暂存吗?
- c# - 如何在控制器之外获取 Request.Scheme 属性。.(净核 2.2)
- geotiff - 无法使用光栅获得单波段 tiff 图像的彩色图
- ssas - 具有行安全过滤器和对象级安全过滤器的两个角色的用户
- java - ArrayList null 不为空
- go - Go - 基于字符串返回包错误的最佳方法?
- azure-pipelines - Microsoft.TeamFoundation.Build.WebApi 在将工件与构建进行排队之前将其与构建相关联
- javascript - JS:如何在不不断发出请求的情况下更新来自端点的数量?
- python - 缺少 2 个口味和勺子所需的位置参数?
- .net - 拥有大量大型对象且您永远不想水合的实体 - 推荐的模式是什么?