Samhan Salahuddin Samhan Salahuddin - 1 month ago 6x
iOS Question

Dismiss a view when a user taps anywhere outside the view

I have a very complex app with lots of stacked views which contain lots of buttons ,drawing areas and other custom touch handling . I am displaying a draggable helper view which can be on top of all the other views . I need to dismiss this view if the user taps anywhere outside the helper view . I have tried using multiple UIWindows and adding Gesture recognizers to the UIWindow .


A easy is to add a transparent button which bounds is equal the superview's bounds. And the superview insert the transparent button below your helper view.

The transparent button add a click event which can dismiss the helper view and the transparent button it self.

For example :

UIButton *transparencyButton = [[UIButton alloc] initWithFrame:superview.bounds];
transparencyButton.backgroundColor = [UIColor clearColor];
[superview insertSubview:transparencyButton belowSubview:helperView];
[transparencyButton addTarget:self action:@selector(dismissHelper:) forControlEvents:UIControlEventTouchUpInside];

and the dismissHelper: method can do this :

- (void)dismissHelper:(UIButton *)sender
    [helperView dismiss];
    sender.hidden = YES;
    // or [sender removeFromSuperview]