UIButton touchDragEnter and touchDragExit called too often - ios

How can I avoid a UIButtons .touchDragEnter and .touchDragExit functions from rapid firing? This question demonstrates the issue perfectly, but the only answer does not describe how to work around it. I'm trying to animate a button when the users finger on the button, and animate it again when their finger slides off. Are there any better ways to do this? If not, how should I stop my animation code from firing multiple times when the users finger is right between an .enter and an .exit state?

You could instead track the location of the touch point itself and determine when the touch point moves in and out of the button
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
if let touch = touches.first {
let point = t.location(in: self)
// moving in to the button
if button.frame.contains(point) && !wasInButton {
// trigger animation
wasInButton = true
}
// moving out of the button
if !button.frame.contains(point) && wasInButton {
// trigger animation
wasInButton = false
}
}
}
wasInButton could be a boolean variable set to true when there is a touch down in the button's frame:
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
if let touch = touches.first {
let point = t.location(in: self)
if button.frame.contains(point) {
wasInButton = true
// trigger animation
} else {
wasInButton = false
}
}
This would require you to subclass the button's superview. And since you might not want to animate as soon as the point leaves the button's frame (because the user's finger or thumb would still be covering most of the button), you could instead do the hit test in a larger frame that encapsulates your button.

Related

Issues with UIScrollView and touchesBegan

When a user touches one of the white UIViews, it runs its touchesBegan:
...
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
delegate.startedTouchingPage(page: self)
...
The delegate is the VC. startedTouchingPage is implemented in the VC as
func startedTouchingPage(page: Page) {
if (page.tool == .PEN || page.tool == .ERASER) {
scrollView.isScrollEnabled = false
scrollView.panGestureRecognizer.isEnabled = false
}
}
I thought this would prevent scrolling and panning, and allow the pen to draw in peace. But instead, when I try to draw on the page, the pen sometimes draws properly, and sometimes instead scrolls the page.
It turns out that the times that the page scrolls instead of draws, touchesBegan didn't run, and thus startedTouchingPage didnt run either. I can't figure out why...

Custom UIGestureRecognizer for a two finger gesture

I have a custom UIGestureRecognizer for a two finger gesture that works perfectly except for it being very picky about how simultaneously the fingers have to touch the iOS-device for touchesBegan to be called with 2 touches. touchesBegan is often called with only one Touch even though I am trying to use two fingers.
Is there any way to make recognition for the number of Touches more forgiving in regards to how simultaneously you have to place your fingers on the touch screen?
I've noticed that a two finger tap is recognized even when you place first one finger and then another much later while still holding the first finger down.
Here is the code for my touchesBegan function:
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent) {
if touches.count != 2 {
state = .failed
return
}
// Capture the first touch and store some information about it.
if trackedTouch == nil {
trackedTouch = touches.min { $0.location(in: self.view?.window).x < $1.location(in: self.view?.window).x }
strokePhase = .topSwipeStarted
topSwipeStartPoint = (trackedTouch?.location(in: view?.window))!
// Ignore the other touch that had a larger x-value
for touch in touches {
if touch != trackedTouch {
ignore(touch, for: event)
}
}
}
}
For two-finger gestures, touchesBegan is most likely going to be called twice: once you put the first finger on the screen, and once for the second one.
In the state you keep, you should keep track of both touches (or for that matter, all current touches), and only start the gesture once both touches have been received and the gesture's start condition has been met.
public class TwoFingerGestureRecognizer: UIGestureRecognizer {
private var trackedTouches: Set<UITouch> = []
public override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent) {
for touch in touches {
if self.trackedTouches.count < 2 {
self.trackedTouches.insert(touch)
}
else {
self.ignore(touch, for: event)
}
}
if self.trackedTouches.count == 2 {
// put your current logic here
}
}
public override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent) {
}
public override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent) {
self.trackedTouches.subtract(touches)
}
public override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent) {
self.trackedTouches.subtract(touches)
}
public override func reset() {
super.reset()
self.trackedTouches = []
}
}
don't worry about touchesBegan:withEvent: instead use touchesEnded:withEvent: or touchesMoved:withEvent: if the end state does not contain both fingers, set it as .failed otherwise set it as .ended
tapping the screen with more than one finger simultaneously is impossible, so during touchesMoved:withEvent: you will find two fingers. I'm not sure about touchesEnded:withEvent: this one probably won't work since removing two fingers simultaneously is just as hard as applying two fingers simultaneously, but it's worth a try to see how it reacts.
I'd recommend making your code a little more forgiving. Although touchesBegan/Moved/Ended/Cancelled respond to events of "one or more touches" (as stated in the Apple docs) relying on the precision of a user to simultaneously touch the screen with 2 fingers is not ideal. This is assuming you have multi-touch enabled, which it sounds like you do.
Try tracking the touches yourself and executing your logic when you're collection of touches reaches 2. Obviously you'll also have to track when your touch amount becomes more or less and handle things accordingly, but I'd guess you're already handling this if you're gesture is meant to be for 2 fingers only (aside from the extra logic you'd have to add in touchesBegan).
Not sure why the other guys answering with using touchesMoved:withEvent did not answer your question, but maybe you need a github example.
Double touch move example.
Is touchesMoved an option in order for you to achieve the desire outcome? Also you could implement a counter before setting the state to failed
Don't forget to set isMultipleTouchEnabled = true
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
if touches.count != 2 {
print("we do NOT have two touches")
if counter > 100 { // 100 "more fogiven"
state = .failed
}
counter += 1
return
} else {
print("we have to two touches")
}

SpriteKit - Quick touches cause wrong behaviour

I am currently working at a sidescroller game, in which the jump height depends on how long the player presses the right half of the screen.
Everything works just fine, except if the user touches the screen quickly. This causes the jump to be as big as possible.
Am I doing something wrong or is this just a problem with the way SpriteKit works?
How can I solve this problem?
EDIT: Here are all the methods handling touches in my game:
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?)
{
for touch in touches
{
swiped = false
let location = touch.location(in: cameraNode)
DispatchQueue.main.asyncAfter(deadline: .now() + 0.065)
{
if self.swiped == false
{
if location.x < 0
{
self.changeColor()
}
else
{
self.jump()
}
}
}
}
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?)
{
for touch in touches {
let location = touch.location(in: cameraNode)
if location.x > 0
{
// Right
thePlayer.endJump()
}
}
}
And then there is also a gesture recognizer handling swiping left and right, with the following handlers:
#objc func swipedRight()
{
if walkstate != .walkingRight
{
walkstate = .walkingRight
}
else
{
boost(direction: 0)
}
swiped = true
}
#objc func swipedLeft()
{
if walkstate != .walkingLeft
{
walkstate = .walkingLeft
}
else
{
boost(direction: 1)
}
swiped = true
}
Hopefully this is enough to describe the problems. The code above is everything I am doing to handle touches.
Well, the problem was, that I am using a DispatchQueue command to call the jumping method after a short delay, in case the user swiped and not tapped. As a result the touchesEnded method gets called before the jump has even started and thus can not be stopped anymore.
To solve this problem I added a boolean variable which is set to true as soon as the player touches the screen and set to false whenever the users finger leaves the screen. In order to jump this variable has to be set to true and thereby the character will not jump after a quick touch anymore.

iOS UIPanGestureRecognizer: adjust sensitivity?

My question: Is there a way to adjust the "sensitivity" of UIPanGestureRecognizer so that it turns on 'sooner', i.e. after moving a fewer number of 'pixels'?
I have a simple app with a UIImageView, and pinch and pan gesture recognizers tied to this so that the user can zoom in and draw on the image by hand. Works fine.
However, I notice the stock UIPanGestureRecognizer doesn't return a value of UIGestureRecognizerState.Changed until the user's gesture has moved about 10 pixels.
Example: Here's a screenshot showing several lines that I've attempted to draw shorter & shorter, and there is a noticeable finite length below which no line gets drawn because the pan gesture recognizer never changes state.
IllustrationOfProgressivelyShorterLines.png
...i.e., to the right of the yellow line, I was still trying to draw, and my touches were being recognized as touchesMoved events, but the UIPanGestureRecognizer wasn't firing its own "Moved" event and thus nothing was getting drawn.
(Note/clarification: That image takes up the entirety of my iPad's screen, so my finger is physically moving more than an inch even in the cases where no state change occurs to the recognizer. It's just that we're 'zoomed in' in terms of the tranformation generated by the pinch gesture recognizer, so a few 'pixels' of the image take up a significant amount of the screen.)
This is not what I want. Any ideas on how to fix it?
Maybe some 'internal' parameter of UIPanGestureRecognizer I could get at if I sub-classed it or some such? I thought I'd try to sub-class the recognizer in a manner such as...
class BetterPanGestureRecognizer: UIPanGestureRecognizer {
var initialTouchLocation: CGPoint!
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent) {
super.touchesBegan(touches, withEvent: event)
initialTouchLocation = touches.first!.locationInView(view)
print("pan: touch begin detected")
print(self.state.hashValue) // this lets me check the state
}
override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent) {
super.touchesMoved(touches, withEvent: event)
print("pan: touch move detected")
print(self.state.hashValue) // this remains at the "began" value until you get beyond about 10 pixels
let some_criterion = (touches.first!.isEqual(something) && event.isEqual(somethingElse))
if (some_criterion) {
self.state = UIGestureRecognizerState.Changed
}
}
}
...but I'm not sure what to use for some_criterion, etc.
Any suggestions?
.
Other alternatives that could work, but that I'd rather not have to do:
I could simply attach my UIPanGestureRecognizer to some parent,
non-zoomed view, and then use affine transforms & such to remap the
points of the pan touches onto the respective parts of the image.
So why am I not doing that? Because the code is written so that
lots of other objects hang off the image view and they all get the
same gesture recognizers and....everything works just great without
my having keep track of anything (e.g. affine transformations), and the problem only shows up if you're really-really zoomed in.
I could abandon UIPanGestureRecognizer, and effectively just write my own using touchesBegan and touchesMoved (which is kind of
what I'm doing), however I like how UIPanGestureRecognizer
differentiates itself from, say, pinch events, in a way that I don't
have to worry about coding up myself.
I could just specify some maximum zoom beyond which the user can't go. This fails to implement what I'm going for, i.e. I want to allow for fine-detail level of manipulation.
Thanks.
[Will choose your answer over mine (i.e., the following) if merited, so I won't 'accept' this answer just yet.]
Got it. The basic idea of the solution is to change the state whenever touches are moved, but use the delegate method regarding simultaneous gesture recognizers so as not to "lock" out any pinch (or rotation) gesture. This will allow for one- and/or multi-fingered panning, as you like, with no 'conflicts'.
This, then, is my code:
class BetterPanGestureRecognizer: UIPanGestureRecognizer, UIGestureRecognizerDelegate {
var initialTouchLocation: CGPoint!
override init(target: AnyObject?, action: Selector) {
super.init(target: target, action: action)
self.delegate = self
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent) {
super.touchesBegan(touches, withEvent: event)
initialTouchLocation = touches.first!.locationInView(view)
}
override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent) {
super.touchesMoved(touches, withEvent: event)
if UIGestureRecognizerState.Possible == self.state {
self.state = UIGestureRecognizerState.Changed
}
}
func gestureRecognizer(_: UIGestureRecognizer,
shouldRecognizeSimultaneouslyWithGestureRecognizer:UIGestureRecognizer) -> Bool {
if !(shouldRecognizeSimultaneouslyWithGestureRecognizer is UIPanGestureRecognizer) {
return true
} else {
return false
}
}
}
Generally setting that "shouldRecognizeSimultaneouslyWithGestureRecognizer" delegate to true always is what many people may want. I make the delegate return false if the other recognizer is another Pan, just because I was noticing that without that logic (i.e., and making the delegate return true no matter what), it was "passing through" Pan gestures to underlying views and I didn't want that. You may just want to have it return true no matter what. Cheers.
Swift 5 + small improvement
I had a case when accepted solution conflicted with basic taps on toolbar which also had this betterPanGesture so I added minimum horizontal offset parameter to trigger state changing to .changed
class BetterPanGestureRecognizer: UIPanGestureRecognizer {
private var initialTouchLocation: CGPoint?
private let minHorizontalOffset: CGFloat = 5
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent) {
super.touchesBegan(touches, with: event)
self.initialTouchLocation = touches.first?.location(in: self.view)
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent) {
super.touchesMoved(touches, with: event)
if self.state == .possible,
abs((touches.first?.location(in: self.view).x ?? 0) - (self.initialTouchLocation?.x ?? 0)) >= self.minHorizontalOffset {
self.state = .changed
}
}
}

recognizing long press gesture in spriteKit

Hi I am currently moving a sprite by checking if the button was pressed in touchesBegan and then updating the position in update. I am doing this so that the user does not need to keep pressing the move up/down/left/right etc button over and over. The problem is that sometimes the sprite does not stop moving which im sure is due to this. Does anyone know a better solution to this? For brevity I will show you the way I am taking care of the up button.
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
for touch: AnyObject in touches {
// Get the location of the touch in this scene
let location = touch.locationInNode(self)
// Check if the location of the touch is within the button's bounds
if upButton.containsPoint(location) {
upButtonPressed = true
}
override func update(currentTime: CFTimeInterval) {
if upButtonPressed == true {
ball.position.y += 3
}
I kept it simple here but I do have all the conditions to stop movement in my code. I am simply wondering if there is an easier way to do this with maybe a long press gesture recognizer?

Resources