开发者

Catch all touch events in UIView?

I want a timer to reset every time the user is touching the screen in my app (So i know that user are still using the device). I have implemented touchBegan in my ViewController.

The problem is if i have a UITableView in my ViewController and user touches the UITableView the function touchBegan is never being called. Reason is that the tableView dosn't pass along the touch event.

What i've understand you can either subclass UITableView to pass it to it's superview or add a transparent UIView on开发者_StackOverflow社区 top that only catches touch event and passing them. Problem with subclassing is that i need to do it on all classes that catches touch event.

Is there a better solution? If not how do you pass the event to it's superview?


Off the top of my head, you could subclass UIWindow or UIApplication and override sendEvent:(UIEvent *)event and take action from there.

e.x. (if you override UIApplication)

- (void)sendEvent:(UIEvent *)event {
   if (event.type == UIEventTypeTouches)
      [(YourApplicationDelegate *)self.delegate wakeUp:event];
   [super sendEvent:event];
}  

This may be a bit invasive for what you're trying to do. Would love to see some other ideas.


The above solutions no longer work with iOS 7.

If you just want to know when the screen was touched, put the following in your ViewController.m file...

- (BOOL)gestureRecognizer:(UIGestureRecognizer*)gestureRecognizer 
                                                shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer*)otherGestureRecognizer
{
  if (otherGestureRecognizer.state == UIGestureRecognizerStateBegan)
  {
    // yes, it was touched!
  }
  return YES;
}


I don't think you should subclass UIScrollView (or UITableView - that extends from UIScrollView) just to handle touch events, as there are some other ways to accomplish what you might be looking for in a cleaner way.

When using UISCrollView or MKMapView (which does not pass along the touch events as well) I generally use an UIGestureRecognizer to catch the specific touch events that I am looking for.

For some specific cases, as handling the touch of a UITableView in the screen just to dismiss a keyboard, I set the UIScrollView property userInteractionEnable to NO at the textViewDidBeginEditing UITextView delegate method, and then set userInteractionEnable to YES at textViewDidEndEditing. Doing this will enable me to catch the touchesBegan without subclassing anything.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜