0

If there is a uiscrollview and and multiple sub view on the uiscrollview. how to know where the user touches i.e on specific view or scrollview(blank space)

pradeep
  • 413
  • 2
  • 7
  • 20

2 Answers2

5

Use this approach:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
        UITouch *touch = [touches anyObject];
        NSLog(@"View touched: %@", touch.view);
}

This method is called every time your finger touches the screen, and the touch knows which view it touched.

Edit: It won't work on a UIScrollView because the scroll view gets the touch itself, check this:

touchesBegan method not called when scrolling in UIScrollView

How to enable touch began in UIScrollView?

Community
  • 1
  • 1
Antonio MG
  • 20,382
  • 3
  • 43
  • 62
3

You have 2 possibilities for detect the touch with - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event; in a scrollView:

first, implement this method in your viewController, and add the scrollview on this viewController.

second, which I recommend: make a custom class which is inherited from UIScrollView like this: .h:

@interface CustomScrollView : UIScrollView 

@end

.m:

#import "CustomScrollView.h"


@implementation CustomScrollView

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [self.nextResponder touchesBegan:touches withEvent:event];
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
    if(!self.dragging){
        [self.nextResponder touchesMoved:touches withEvent:event];
    }
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
    [self.nextResponder touchesEnded:touches withEvent:event];
}

@end

in your vc make:

...

CustomScrollView* customScrollView = [[CustomScrollView alloc]initWithFrame:CGRectMake(0, 0, 320, 480)];

...

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
        UITouch *touch = [touches anyObject];
        NSLog(@"View touched: %@", touch.view);
}
Magyar Miklós
  • 4,182
  • 2
  • 24
  • 42