views:

736

answers:

3

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?

A: 

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.

Arseniy Banayev
And, per my self-answer below, make user userInteractionEnabled=NO for the scrollview
wgpubs
A: 

You need to disable user interaction with the scroll view as such ...

scrollView.userInteractionEnabled = NO;

Once disabled, the UIScrollView's superview gets the touchesBegan event.

wgpubs
+1  A: 

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.

Vladimir