Reputation: 8432
I'm building a SwiftUI macOS app.
I've got a basic Rectangle shape with a drag gesture on it.
In the onEnded
handler, I am wanting to determine if the user has effectively tapped on the object. I do this by checking that the width and height of the translation are both zero.
(There are reasons I'm not using a tap gesture).
Rectangle()
.size(.init(width:50, height: 50))
.fill(Color.blue.opacity(0.01))
.gesture(DragGesture(minimumDistance:0)
.onChanged { gesture in
// Ommited
}
.onEnded { gesture in
print("startLocation", gesture.startLocation)
print("start", gesture.location)
print("translation", gesture.translation)
if gesture.translation == .zero {
print("tap")
}
print()
}
)
I'm getting issues where translations are being reported with unexpected values.
The values reported differ based on where I click in the rectangle.
Here's a set of groups of individual clicks. The translation
is derived from the startLocation
and location
fields.
You can see variation between the startLocation
and the location
fields. If it was a very small variation I could debounce, however the fact that sometimes I get a value of 3
makes me wonder why such a variation could happen (I'm being over the top careful to execute the click without movement).
Does anyone know why this variation is creeping in?
startLocation (263.5149841308594, 144.3092803955078)
start (263.51495361328125, 144.30926513671875)
translation (-3.0517578125e-05, -1.52587890625e-05)
startLocation (276.2882995605469, 144.43479919433594)
start (276.288330078125, 144.434814453125)
translation (3.0517578125e-05, 1.52587890625e-05)
startLocation (274.3827209472656, 162.3402557373047)
start (274.38275146484375, 162.34027099609375)
translation (3.0517578125e-05, 1.52587890625e-05)
startLocation (264.81805419921875, 167.47662353515625)
start (264.81805419921875, 167.47662353515625)
translation (0.0, 0.0)
tap
startLocation (254.5931396484375, 135.4690399169922)
start (254.5931396484375, 135.46905517578125)
translation (0.0, 1.52587890625e-05)
startLocation (259.1647033691406, 140.26919555664062)
start (259.16473388671875, 140.26919555664062)
translation (3.0517578125e-05, 0.0)
As pointed out below, the value of 3
is actually 3e-05 = 0.00003
which I missed at the time of writing. However, still looking for information as to why the tap gesture will have zero translation on repeated clicks in some points of the Rectangle, but have a non zero translation in others.
Upvotes: 1
Views: 798
Reputation: 1256
How about this?
if gesture.translation.width/UIScreen.main.bounds.width < 0.05 &&
gesture.translation.height/UIScreen.main.bounds.height < 0.05
{
print("tap") // 0.01 ~ 0.05
}
This way works, regardless of the size of the device and width & height, it is always constant as it falls in percentages.
Upvotes: 0