how to detect event touch in subview or how to make parent view was touched when we touch subview?
I have 2 UIView.
the first one is a parent view
the second one is a subview,
how can we detect when a subview was touched?
or I want to make parent view was touched when user 开发者_StackOverflow社区touch subview, any code can help me to do it? is it possible to do this?
because I have a Something Function, that will call when one of them was touched.
This worked for me:
(Link the subview in xib or storyboard)
ViewController.h
@interface ViewController : UIViewController
@property (nonatomic, strong) IBOutlet UIView *subview;
@property (nonatomic, strong) UITapGestureRecognizer *tapRecognizer;
@end
ViewController.m
@implementation ViewController
@synthesize subview;
@synthesize tapRecognizer;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self
action:@selector(handleTap:)];
[subview addGestureRecognizer:tapRecognizer];
}
- (IBAction)handleTap:(UITapGestureRecognizer *)recognizer {
if (recognizer.state == UIGestureRecognizerStateEnded){
//code here
NSLog(@"subview touched");
}
}
@end
The problem has been solved. I think someone gave a great answer but I forget how.
This is what I did. There is an option in XIB. There is a checkbox (titled "User interaction enabled") that specifies whether a subview handle user event or not.
Uncheck that checkboxes and all touch to the subview goes to the parent view or whatever other view behind it.
to detect touch event you need to add UITapGestureRecognizer
in your sub view or super view (in which you want get touch).
- (void)viewDidLoad
{
UITapGestureRecognizer* tap = [[UITapGestureRecognizer alloc] initWithTarget:self
action:@selector(tap:)];
tap.numberOfTapsRequired = 1;
[self addGestureRecognizer:tap];
[super viewDidLoad];
}
then you can add delegate methods of UITapGestureRecognizer
- (void) touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event
{
UITouch *touch = [touches anyObject];
// here you can get your touch
NSLog(@"Touched view %@",[touch.view class] );
}
hope it gives you idea..
This might help:
UITouch *touch = [event.allTouches anyObject];
CGPoint touchPoint = [touch locationInView:YOUR VIEW NAME];
精彩评论