用拖动手势增加计数



你能告诉我使用DragGesture时是否可以增加/减少计数器吗,下面是代码:

struct ContentView: View {
@State private var count: Int = 0
@State private var offset: CGSize = .zero
var body: some View {
VStack(spacing: 15) {
Text("(count)")
RoundedRectangle(cornerRadius: 10)
.frame(width: 250, height: 350)
.foregroundColor(.white)
.shadow(color: .black, radius: 10)
.offset(x: offset.width)
.gesture(DragGesture()
.onChanged { value in
withAnimation(.spring()) {
offset = value.translation
if offset.width > 150 {
count += 1
} else if offset.width < -150 {
count -= 1
}
}
}
.onEnded { value in
withAnimation(.spring()) {
offset = .zero
}
})
}
}
}

问题是计数器在克服x轴条件下设置的坐标后不断增加/减少,想法是增加/减少1,图形返回到初始位置,添加以下代码也没有帮助:

.onChanged { value in
withAnimation(.spring()) {
offset = value.translation
if offset.width > 150 {
count += 1
offset = .zero
} else if offset.width < -150 {
count -= 1
offset = .zero
}
}
}

请告诉我如何完成这项任务。

这里的问题是如何更改计数。你要做的是用偏移量的余数除以你想要在增加之前拖动的移动量。举个例子,以一把尺子为例。你把手指放在1上,然后往上拖。在数到2之前,你不希望有任何改变。一旦你到达2,并继续拖动,你不希望任何改变,直到你到达3。这就是余数告诉你拖拽150个点的次数。如果你想让它更快地改变,从150分开始减少,少一点,增加它。

编辑下面更正我的数学错误。(我不应该尝试在手机上编程):

要除以偏移量。高度乘以150(或任何您想要触发更改的移动量),并使用整数商作为计数。所以,你可以这样修改你的代码:

.onChanged { value in
withAnimation(.spring()) {
offset = value.translation
// You want the quotient of the offset / 150
// Then take the additive inverse for iOS coordinates. (remove the - for macOS)
count = -Int(offset.height / 150)
}
}

最新更新