小智 8
相当老的问题,但在其他地方没有找到答案。
您可以轻松检查是向左滑动还是向右滑动,因为手势会返回其最终状态,其中包含起始位置和最终位置。
Text("Hello")
.gesture(
DragGesture(minimumDistance: 100)
.onEnded { endedGesture in
if (endedGesture.location.x - endedGesture.startLocation.x) > 0 {
print("Right")
} else {
print("Left")
}
}
Run Code Online (Sandbox Code Playgroud)
是的,它是通过将手势平移的两个组件(水平或垂直)之一应用于视图偏移。
这是实现为ViewModifier.
struct DraggableModifier : ViewModifier {
enum Direction {
case vertical
case horizontal
}
let direction: Direction
@State private var draggedOffset: CGSize = .zero
func body(content: Content) -> some View {
content
.offset(
CGSize(width: direction == .vertical ? 0 : draggedOffset.width,
height: direction == .horizontal ? 0 : draggedOffset.height)
)
.gesture(
DragGesture()
.onChanged { value in
self.draggedOffset = value.translation
}
.onEnded { value in
self.draggedOffset = .zero
}
)
}
}
Run Code Online (Sandbox Code Playgroud)
演示:
struct ContentView: View {
var body: some View {
VStack {
Spacer(minLength: 100)
HStack {
Rectangle()
.foregroundColor(.green)
.frame(width: 100, height: 100)
.modifier(DraggableModifier(direction: .vertical))
Text("Vertical")
}
Spacer(minLength: 100)
Rectangle()
.foregroundColor(.red)
.frame(width: 100, height: 100)
.modifier(DraggableModifier(direction: .horizontal))
Text(verbatim: "Horizontal")
Spacer(minLength: 100)
}
}
}
Run Code Online (Sandbox Code Playgroud)
结果:
| 归档时间: |
|
| 查看次数: |
2324 次 |
| 最近记录: |