Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect ANY touch in a view (iPhone SDK)

I'm currently using ...

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {

to detect swipes. I've got everything working. The only problem is if the user touches on top of something (eg a UIButton or something) the - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { is not called. Is there something like touchesBegan but will work if I touch ANYWHERE on the view?

Thanks in advance, David

like image 934
bobbypage Avatar asked Apr 11 '10 02:04

bobbypage


1 Answers

Touch events propagate like this:

  1. UIViews get sent -hitTest:withEvent: recursively until some UIView decides that the touch is inside its bounds and not inside any user-interaction-enabled subview.
  2. UIWindow sends -touchesBegan:withEvent: and friends to the UIView returned in step 1, ignoring any view hierarchy.

In other words, -hitTest:withEvent: is used to determine the target view for the touch, after which the target view gets all -touches...:withEvent: messages. If you need to intercept the swipe gesture which may begin in a UIButton, you will have to override -hitTest:withEvent: to return self.

But there's a problem with this approach. Once you do that, your button will stop working because it won't get any -touches...:withEvent: messages. You will have to forward touches to subviews manually unless you detect a swipe gesture. That is a serious pain in the butt and is not guaranteed to work at all. That's what UIGestureRecognizers are for.

Another approach is to subclass UIWindow and override -sendEvent:, which may work better in your case.

Anyway, make sure you read the Event Handling documentation thoroughly. Among other scary warnings it says:

The classes of the UIKit framework are not designed to receive touches that are not bound to them; in programmatic terms, this means that the view property of the UITouch object must hold a reference to the framework object in order for the touch to be handled.

like image 112
Costique Avatar answered Sep 22 '22 13:09

Costique