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)t开发者_如何学运维ouchesBegan:(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
Touch events propagate like this:
- 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.
- 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.
I think you have to have one or the other. Do you want the iPhone to detect the touch on top of the button or the touch on top of the view? I don't think you can do both at the same time and I would be surprised if you could. Sorry for not having a better answer for you...
精彩评论