Last active
September 2, 2024 07:37
-
-
Save heestand-xyz/311f7f2a239b8e5dfe0f9da9e5f26a46 to your computer and use it in GitHub Desktop.
Cancellable Drag Gesture
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import SwiftUI | |
struct ContentView: View { | |
@State private var isDragging: Bool = false | |
@GestureState private var isDraggingActive: Bool = false | |
var body: some View { | |
ZStack { | |
if isDragging { | |
Color.green | |
} else { | |
Color.red | |
} | |
} | |
.gesture( | |
DragGesture() | |
.updating($isDraggingActive) { _, isDraggingActive, _ in | |
isDraggingActive = true | |
} | |
.onChanged { value in | |
if !isDragging { | |
/// Started | |
isDragging = true | |
} | |
/// Update | |
} | |
.onEnded { _ in | |
/// Ended | |
isDragging = false | |
} | |
) | |
.onChange(of: isDraggingActive) { _, isDraggingActive in | |
if isDragging, !isDraggingActive { | |
/// Cancelled | |
isDragging = false | |
} | |
} | |
} | |
} | |
#Preview { | |
ContentView() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment