Jonathan Thurft
Jonathan Thurft

Reputation: 4173

Close subview when the parent view is touched

I have parentView and subView childView. childView is positioned in the middle of my parentView and is about half it's size.

I want to close childView when user tap on the parentView.

My code as follows creates a UITapGestureRecognizer in the parentView once the childView is open.

My problem is that the tap event is triggered when the user touches any view, not just the parentView.

Thus, I was wondering how can I just make the event happen if ONLY the parentView is touched or any other possible to close the sub view if the parent is touched.

- (IBAction)selectRoutine:(id)sender {
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Storyboard" bundle:nil];

    createRoutinePopupViewController* popupController = [storyboard instantiateViewControllerWithIdentifier:@"createRoutinePopupView"];

    popupController.view.center = CGPointMake(self.view.bounds.size.width / 2, self.view.bounds.size.height / 2);
    _ass = popupController;
    //Tell the operating system the CreateRoutine view controller
    //is becoming a child:
    [self addChildViewController:popupController];

    //add the target frame to self's view:
    [self.view addSubview:popupController.view];

    //Tell the operating system the view controller has moved:
    [popupController didMoveToParentViewController:self];

    UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTap:)];

    [singleTap setNumberOfTapsRequired:1];

    [self.view addGestureRecognizer:singleTap];

}
-(void) handleSingleTap: (id) sender {
    NSLog(@"TEST STRING");
}

Upvotes: 0

Views: 701

Answers (1)

HarshIT
HarshIT

Reputation: 4915

You need to use UIGestureRecognizerDelegate , implement following method.

it will check the touched view.

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    if( [touch view] != popupController.view)
        return YES;

    return NO;
}

Upvotes: 2

Related Questions