An extension to SwiftUI that will add control events to your views.
Download the DragGestureObserver.swift file and add it to your project.
func dragGestureObserver() -> some View
func onDragGesture(_ phase: DragGesture.Phase, action: @escaping (DragGestureProxy) -> Void) -> some View
func onDragGesture(_ phases: [DragGesture.Phase] = DragGesture.Phase.allCases, action: @escaping (DragGestureProxy) -> Void) -> some View
extension DragGesture {
enum Phase: CaseIterable {
case down
case downInside
case downOutside
case up
case upInside
case upOutside
case move
case moveInside
case moveOutside
case enter
case exit
}
}
struct DragGestureProxy {
let phase: DragGesture.Phase
let value: DragGesture.Value
let geometry: GeometryProxy
}
The .dragGestureObserver()
modifier needs to be attached to a container view. This will listen for the drag gesture within the container size.
After that you can attach the .onDragGesture(action:)
on any subview of the container to start receiving those events.
import SwiftUI
struct ContentView: View {
@State private var isPressed: Bool = false
var body: some View {
VStack {
Text("Click Me")
.fontWeight(.bold)
.foregroundStyle(isPressed ? .blue : .white)
.padding()
.onDragGesture([.downInside, .up]) { proxy in
self.isPressed = (proxy.phase == .downInside)
}
}
.dragGestureObserver()
}
}
If you have been enjoying my free Swift file, please consider showing your support by buying me a coffee through the link below. Thanks in advance!