如何使用 SwiftUI 在视图上检测向上、向下、向左和向右滑动 [英] How to detect Swiping UP, DOWN, LEFT and RIGHT with SwiftUI on a View
问题描述
我正在构建 Apple Watch 应用.
I'm getting into building Apple Watch apps.
我目前正在做的工作需要我在四个主要方向(UP
、DOWN
、LEFT
> 和 RIGHT
)
What I'm currently working on will require me to make use of detecting swipes in the four main directions (UP
, DOWN
, LEFT
and RIGHT
)
问题是我不知道如何检测到这一点.我环顾四周,却走到了尽头.
The problem is I have no idea how to detect this. I've been looking around and I'm reaching dead ends.
当用户在视图上滑动 UP
时,我可以对下面的视图执行什么操作以仅打印 swiped
?
What can I do to my view below to just print swiped up
when the user swipes UP
on the view?
struct MyView: View {
var body: some View {
Text("Hello, World!")
}
}
谢谢.
推荐答案
如果你想要一个更宽容"的方案对于滑动的方向性,您可以使用更多条件来帮助平衡:
If you want one that is more "forgiving" to the directionality of the swipe, you can use a few more conditionals to help even it out:
做了一些更多的测试,显然第二个条件的值增加了一些混乱,所以我调整它们以消除所说的混乱并使手势防弹(拖动到角落现在会出现无线索"而不是其中一个手势)...
did some more testing, apparently the values for the second conditional add some confusion, so I adjusted them to remove said confusion and make the gesture bulletproof (drags to the corners will now come up with "no clue" instead of one of the gestures)...
let detectDirectionalDrags = DragGesture(minimumDistance: 3.0, coordinateSpace: .local)
.onEnded { value in
print(value.translation)
if value.translation.width < 0 && value.translation.height > -30 && value.translation.height < 30 {
print("left swipe")
}
else if value.translation.width > 0 && value.translation.height > -30 && value.translation.height < 30 {
print("right swipe")
}
else if value.translation.height < 0 && value.translation.width < 100 && value.translation.width > -100 {
print("up swipe")
}
else if value.translation.height > 0 && value.translation.width < 100 && value.translation.width > -100 {
print("down swipe")
}
else {
print("no clue")
}
这篇关于如何使用 SwiftUI 在视图上检测向上、向下、向左和向右滑动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!