Gestures in SwiftUI
Just collect all the Gestures codes here
What are Gestures types available in swiftUI
- onTapGesture
- onLongPressGesture
- highPriorityGesture
- simultaneousGesture
- DragGesture
onTapGesture
onTapGesture will triggered when tap happened
Text("Hello, World!")
.onTapGesture() {
print("tapped!")
}
Output when tapped on Hello, world!
Text
tapped!
Double tap Gesture
We just adding some count in onTapGesture
, so it will triggered when we tap == the count
Text("Hello, World!")
.onTapGesture(count: 2) {
print("Double tapped!")
}
Output when tapped on Hello, world!
Text
Double tapped!
onLongPressGesture
Will triggered when we doing a long press.
Text("Hello, World!")
.onLongPressGesture {
print("Long pressed!")
}
Output when long pressed on Hello, world!
Text
Long pressed!
We can also add some long press timing.
Text("Hello, World!")
.onLongPressGesture(minimumDuration: 2) {
print("Long pressed!")
}
And to know the long press process
Text("Hello, World!")
.onLongPressGesture(minimumDuration: 1) {
print("Long pressed!")
} onPressingChanged: { inProgress in
print("In progress: \(inProgress)!")
}
HighPriorityGesture
When we tapped on below code, text tapped
only will be the output VStack tapped
will not get called. so to over come this case, we using HighPriorityGesture
struct ContentView: View {
var body: some View {
VStack {
Text("Hello, World!")
.onTapGesture {
print("Text tapped")
}
}
.onTapGesture {
print("VStack tapped")
}
}
}
output
Text tapped
To over come, we can use
struct ContentView: View {
var body: some View {
VStack {
Text("Hello, World!")
.onTapGesture {
print("Text tapped")
}
}
.highPriorityGesture(
TapGesture()
.onEnded { _ in
print("VStack tapped")
}
)
}
}
And output is
VStack tapped
If sometime we need both to triggered we will go with simultaneousGesture
struct ContentView: View {
var body: some View {
VStack {
Text("Hello, World!")
.onTapGesture {
print("Text tapped")
}
}
.simultaneousGesture(
TapGesture()
.onEnded { _ in
print("VStack tapped")
}
)
}
}
output
Text tappedVStack tapped
DragGesture
Will trigger while dragging or swiping in the view.
.gesture(
DragGesture()
.onChanged { gesture in
print(gesture)
}
.onEnded { gesture in
print(gesture)
}
)
onChanged is while dragging, onEnded while drag is ended.
If any mistake or you need to shout me, comments session in always opened
Nanri vanakkam 🙏