jasan jasan - 3 months ago 13
Swift Question

dismissing menu if tap anywhere else on the screen in Swift?

So I'm using this Menu from github. Currently the menu opens on tap and retracts if you click the tap button again, but I also want the menu to retract if the user taps anywhere else on the screen except the buttons. The problem I'm running into is that I am implementing this in navbar with tabbarcontroller, what happens is that if i tap the button to open the menu and then click on the different tab without collapsing the bubble menu. And then if I come back to the same tab, the bubble menu is visually still open but in code it still thinks it is collapsed, that leads to weird behavior of adding another subview ANy suggestions?

The following is the example of how it works now. ANd here is the link to the Code.
enter image description here


There are 2 approaches:

First approach:

You can set a tag for your button:


An then in your viewcontroller, use the touchesBegan:withEvent: delegate

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{

    UITouch *touch = [touches anyObject];

        //Call your dismiss method


Second approach:

If there's an overlay for your buttons (e.g. the background to highlight your buttons, and fill all over your view) , you can add an UITapGestureRecognizer to it, and add it to your view every time you want your custom view to show up. Here's an example:

UIView *overlay;

    //Add the overlay, if there's one in your code, then you don't have to create this
        overlay = [[UIView alloc] initWithFrame:CGRectMake(0,  0,self.view.frame.size.width, self.view.frame.size.height)];
    [overlay setBackgroundColor:[UIColor colorWithRed:0 green:0 blue:0 alpha:0.5]];

    //Register the tap gesture recognizer
    UITapGestureRecognizer *overlayTap =
    [[UITapGestureRecognizer alloc] initWithTarget:self

    [overlay addGestureRecognizer:overlayTap];

    [self.view addSubview:overlay];

- (void)onOverlayTapped
   //Call your dismiss method

    for (UITapGestureRecognizer *ges in previewOverlay.gestureRecognizers) {
        [overlay removeGestureRecognizer:ges];
    [overlay removeFromSuperview];


You can see my answer here for a similar case.