在我正在开发的一个应用程序中,有一个部分主要是“前进”导航——点击按钮会显示下一张幻灯片。但是,还需要辅助“向后”导航。这是我使用的方法:
import SwiftUI
struct Sample: View {
@State private var dragOffset: CGFloat = -100
var body: some View {
VStack {
Text("Perhaps a title")
ScrollView {
VStack {
Text("Some scrollable content is going to be here")
// ...
Button(action: {
// Go to the next slide
}) { Text("Next") }
}
}
Text("and, maybe, something else")
}
.overlay(
Image(systemName: "arrow.left").offset(x: dragOffset / 2),
alignment: .leading
)
.gesture(
DragGesture()
.onChanged{
self.dragOffset = $0.translation.width
}
.onEnded {
self.dragOffset = -100 // Hide the arrow
if $0.translation.width > 100 {
// Go to the previous slide
}
}
)
}
}
有一个小的指示器(左箭头),最初是隐藏的(dragOffset = -100)。当拖动手势开始时,偏移量被输入到dragOffset 状态变量中,并有效地显示箭头。当拖动手势结束时,箭头再次隐藏,如果达到一定的偏移量,则显示上一张幻灯片。
效果很好,除了当用户滚动 ScrollView 中的内容时,这个手势也会被触发和更新一段时间,但我认为,然后被 ScrollView 取消,并且没有调用“onEnded”。结果,箭头指示符停留在屏幕上。
因此,问题是:做这样的手势的正确方法是什么,它可以与 ScrollView 一起使用? SwiftUI 的当前状态甚至可能吗?
最佳答案
对于这种临时状态,最好使用 GestureState
因为它会在手势取消/完成后自动重置为初始状态。
所以这是可能的方法
演示:
代码:
struct Sample: View {
@GestureState private var dragOffset: CGFloat = -100
var body: some View {
VStack {
Text("Perhaps a title")
ScrollView {
VStack {
Text("Some scrollable content is going to be here")
// ...
Button(action: {
// Go to the next slide
}) { Text("Next") }
}
}
Text("and, maybe, something else")
}
.overlay(
Image(systemName: "arrow.left").offset(x: dragOffset / 2),
alignment: .leading
)
.gesture(
DragGesture()
.updating($dragOffset) { (value, gestureState, transaction) in
let delta = value.location.x - value.startLocation.x
if delta > 10 { // << some appropriate horizontal threshold here
gestureState = delta
}
}
.onEnded {
if $0.translation.width > 100 {
// Go to the previous slide
}
}
)
}
}
注:
dragOffset: CGFloat = -100
这可能对不同的真实设备产生不同的影响,因此最好明确计算它。
关于swiftui - SwiftUI 中 DragGesture 和 ScrollView 的交互,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60305207/