How to add a gesture recognizer to a view
How to add a gesture recognizer to a view 관련
Updated for Xcode 15
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 smaller every time it's tapped:
struct ContentView: View {
@State private var scale = 1.0
var body: some View {
Image("ireland")
.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 halves in size when pressed for at least one second:
struct ContentView: View {
@State private var scale = 1.0
var body: some View {
Image("cornwall")
.scaleEffect(scale)
.gesture(
LongPressGesture(minimumDuration: 1)
.onEnded { _ in
scale /= 2
}
)
}
}
Finally, DragGesture
triggers when the user presses down on a view and moves 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("iceland")
.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("rome")
.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.