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)
Asked
Active
Viewed 217 times
2 Answers
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

Community
- 1
- 1

Antonio MG
- 20,382
- 3
- 43
- 62
-
but it is not getting called when we use scrollview and add sub view to scroll view – pradeep Oct 22 '13 at 09:23
-
Is there any option to detect the touches on scrollview – pradeep Oct 22 '13 at 09:32
-
That method should be triggered whatever it is on the screen. – Antonio MG Oct 22 '13 at 09:39
-
You have to implement this method on the superView, for example self.view – Magyar Miklós Oct 22 '13 at 09:43
-
It is not getting called if the base view is scroll view – pradeep Oct 22 '13 at 09:44
-
USe this: http://stackoverflow.com/questions/3386840/how-to-enable-touch-began-in-uiscrollview or this http://stackoverflow.com/questions/5971819/touchesbegan-method-not-called-when-scrolling-in-uiscrollview – Antonio MG Oct 22 '13 at 09:45
-
1I added a solution to you – Magyar Miklós Oct 22 '13 at 09:53
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