Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How To Detect "Touch Down" in superview of UIScrollView?

I have a UIView that contains a UIScrollView and I want to be able to capture the "Touch Down" event in the UIView any time the user taps on the UIScrollView.

I've tried including all the touchesBegan/Ended/Cancelled handlers in my UIViewController but none of them get fired when tapping inside the UIScrollView contained in the main UIView.

What is the best way to accomplish this?

like image 641
wgpubs Avatar asked Apr 07 '10 21:04

wgpubs


3 Answers

In the UIView, implement touchesBegan:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    // assign a UITouch object to the current touch
    UITouch *touch = [[event allTouches] anyObject];

    // if the view in which the touch is found is myScrollView
    // (assuming myScrollView is the UIScrollView and is a subview of the UIView)
    if ([touch view] == myScrollView) {
        // do stuff here
    }
}

A side note: make sure userInteractionEnabled is set to YES in the UIView.

like image 174
Arseniy Banayev Avatar answered Nov 15 '22 07:11

Arseniy Banayev


You can also implement hitTest:withEvent: in your UIView subclass. This method gets called to determine which subview should receive touch event. So here you can either just track all events passing through your view not or hide some of the events from subviews. In this case you may not need to disable user interaction for your scrollview.

See more details on this method in UIView class reference.

like image 31
Vladimir Avatar answered Nov 15 '22 06:11

Vladimir


You can also add a gesture recognizer to your superview. For example a tap gesture if you need to activate/deactivate things like buttons overlaying the scroll view :

self.tap = [[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onTap:)] autorelease];
tap.numberOfTapsRequired = 1;

["containerView" addGestureRecognizer:tap];

Gestures do preserve the scroll view interaction

like image 20
Menator Avatar answered Nov 15 '22 07:11

Menator