Updated for Xcode 12.5
Any SwiftUI view can have gesture recognizers attached, and those gesture recognizers in turn can have closures attached that will be run when the recognizer activates.
There are several gesture recognizers to work with, and I’m going to provide you with code samples for several of them to help get you started – you’ll see how similar they are.
First, TapGesture
. When you create this you can specify how many taps it takes to trigger the gesture, then attach an onEnded
closure that will be run when the gesture happens. For example, this creates an image that gets bigger every time it’s tapped:
struct ContentView: View {
@State private var scale: CGFloat = 1.0
var body: some View {
Image("example-image")
.scaleEffect(scale)
.gesture(
TapGesture()
.onEnded { _ in
scale += 0.1
}
)
}
}
Second, LongPressGesture
recognizes when the user presses and holds on a view for at least a period of time you specify. So, this creates an image view that prints a message when its pressed for at least two seconds:
struct ContentView: View {
@State private var scale: CGFloat = 1.0
var body: some View {
Image("example-image")
.scaleEffect(scale)
.gesture(
LongPressGesture(minimumDuration: 2)
.onEnded { _ in
scale *= 2
}
)
}
}
Finally, DragGesture
triggers when the user presses down on a view and move at least a certain distance away. So, this creates an image with a drag gesture that triggers when the user moves it at least 50 points:
struct ContentView: View {
@State private var dragCompleted = false
var body: some View {
VStack {
Image("2-17")
.gesture(
DragGesture(minimumDistance: 50)
.onEnded { _ in
dragCompleted = true
}
)
if dragCompleted {
Text("Drag completed!")
}
}
}
}
Drag gestures are particularly good when combined with the offset()
modifier, which lets us adjust the natural position of a view. For example, this offsets an image using a dragOffset
size, which itself is attached to a drag gesture:
struct ContentView: View {
@State private var dragOffset = CGSize.zero
var body: some View {
VStack {
Image("2-17")
.offset(dragOffset)
.gesture(
DragGesture()
.onChanged { gesture in
dragOffset = gesture.translation
}
.onEnded { gesture in
dragOffset = .zero
}
)
}
}
}
If you try that code you’ll see you can drag the image around now, and when you release your finger it snaps back to its original location.
SPONSORED Building and maintaining in-app subscription infrastructure is hard. Luckily there's a better way. With RevenueCat, you can implement subscriptions for your app in hours, not months, so you can get back to building your app.
Sponsor Hacking with Swift and reach the world's largest Swift community!
Link copied to your pasteboard.