1

When the user taps and holds down a UIButton in my app, after a while a UIControlEventTouchCancel event is fired. The Apple documentation for UIControl doesn't have any detailed explanation about this event. Why is it triggered? What is it used for?

[button addTarget:key action:@selector(keyUp:) forControlEvents:UIControlEventTouchUpInside];
[button addTarget:key action:@selector(keyUp:) forControlEvents:UIControlEventTouchUpOutside];
[button addTarget:key action:@selector(keyCancel:) forControlEvents:UIControlEventTouchCancel];
[button addTarget:key action:@selector(keyDown:) forControlEvents:UIControlEventTouchDown];
user3246173
  • 488
  • 6
  • 18

2 Answers2

3

According to the documentation, a UIControlEventTouchCancel event is due to:

A system event canceling the current touches for the control.

Therefore, it's not due to user input that the touch has ended, it's due to a system event (such as a low memory warning, or the app moving into the background). I have no idea why you are able to trigger it from simply pressing and holding on the button.

I'm pretty sure it's a similar (if not caused by the) event to the UIResponder's touchesCancelled:withEvent: event. The documentation on this is slightly more detailed:

This method is invoked when the Cocoa Touch framework receives a system interruption requiring cancellation of the touch event; for this, it generates a UITouch object with a phase of UITouchPhaseCancel. The interruption is something that might cause the application to be no longer active or the view to be removed from the window

Hamish
  • 78,605
  • 19
  • 187
  • 280
  • Memory is fine and the app wasn't moved to the background. I was seeing some anomalies with the button keyDown action and when I added the touch cancel event, it explained the anomaly. However, I can't figure out what is causing the cancel event to trigger. – user3246173 Jan 21 '16 at 19:09
  • hmm... weird. Are you doing anything in the background that could maybe affect the button, such as animations? – Hamish Jan 21 '16 at 19:13
  • I figured it out! My code was removing the button from the view in another method that was refreshing the display. – user3246173 Jan 21 '16 at 19:43
  • ah, makes sense, glad you found it! – Hamish Jan 21 '16 at 19:45
0

One scenario is the screen rotation. If you rotate your screen while holding down the button you will get a touch cancel event.

Max
  • 59
  • 1
  • 4