SwiftUI isn’t perfect yet and it doesn’t have all the possibilities like UIKit. One of them is detecting when the user touched the view but didn’t touch up yet.
The easiest solution to do it is to use DragGesture.
Let’s create Image and make it bigger.
Image(systemName: “star”)
.resizable()
.frame(width: 100, height: 100)
Now add a gesture and create DragGesture with minimumDistance 0.
.gesture(
DragGesture(minimumDistance: 0)
)
DragGesture has two events onChangd and onEnded. The first one will tell you when the user touches down the view and the second one when touches up.
DragGesture(minimumDistance: 0)
.onChanged { value in
print(“Touch down”)
}
.onEnded { value in
print(“Touch up”)
}
Notice that this “touch down” is executed many times when the user starts moving finger across the view.
To prevent making some actions add State property do keep the information when touch down is executed.
@State private var canTouchDown = true
var body: some View {
Image(systemName: “star”)
.resizable()
.frame(width: 100, height: 100)
.gesture(
DragGesture(minimumDistance: 0)
.onChanged { value in
if canTouchDown {
print(“Touch down”)
}
canTouchDown = false
}
.onEnded { value in
print(“Touch up”)
canTouchDown = true
}
)
}