开发者

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

开发者 https://www.devze.com 2022-12-26 15:40 出处:网络
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 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 touchesB开发者_JAVA技巧egan/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?


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.


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.


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


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.

0

精彩评论

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

关注公众号