how to detect event touch in subview or how to make parent view was touched when we touch subview?

user4951 picture user4951 · Aug 2, 2011 · Viewed 15.2k times · Source

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 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.

Answer

justinkoh picture justinkoh · Sep 13, 2012

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