jasan jasan - 4 months ago 8
iOS Question

Dismissing menu if tap anywhere else on the screen in iOS?

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

Answer

There are 2 approaches:

First approach:

You can set a tag for your buttons and other views that you don't want the menu to be dismissed when they get tapped:

button.tag=99;
button2.tag=99;
backgroundImage.tag=99;

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

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


    UITouch *touch = [touches anyObject];

    if(touch.view.tag!=99){
        //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;

-(void)addOverlay{
    //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
                                        action:@selector(onOverlayTapped)];

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