maxkonovalov / MKDropdownMenu

🔻 Dropdown Menu for iOS with many customizable parameters to suit any needs
MIT License
527 stars 83 forks source link

Close 2 or more DropdownMenu on touch outside. #24

Closed jackywongcw closed 7 years ago

jackywongcw commented 7 years ago

Hello, I've tried modifying the code myself, but couldn't do it. Two issues:

  1. DropdownMenu doesn't close when tap outside of dropdown menu, it closes the dropdownMenu ONLY if the tap is "below" the DropdownMenu, if the tap is above, dropdownMenu remains.

  2. If I have 2 dropdownMenu 100px above each other, tapped on bottom's dropdownMenu opens the selection, and because of issue 1, and I tap on the above dropdownMenu, I have 2 expanded dropdownMenu stacking each other now. Is there anyway to fix this? If 2 dropdownMenus are expanded, and I tap on area that is above both dropdownMenu, they won't close..

jackywongcw commented 7 years ago

Adding this method in my .m file will close both dropdownMenu if I tap "above both dropdownmenu"

-(void) touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    UITouch* touch = [touches anyObject];
    if (touch.phase == UITouchPhaseBegan)
    {
        [dropdownMenu1 closeAllComponentsAnimated:YES];
        [dropdownMenu2 closeAllComponentsAnimated:YES];
    }
}
maxkonovalov commented 7 years ago

Hi @jackywongcw, you can add a tap gesture recognizer to your view instead of implementing touchesBegan to be consistent with the menu behavior (when tapped below).

As for both issues, this is the expected behavior. You can take a look at the Example project for reference.

jackywongcw commented 7 years ago

@maxkonovalov With your suggestion of adding a tap gesture recognizer, I've managed to fix both my issue.

Solution for 1st issue: Add tapGestureRecognizer in your parent view

UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(closeDropDownMenu:)];
    [self.view addGestureRecognizer:tap];

Implement the action method:

- (void)closeDropDownMenu:(UITapGestureRecognizer *)recognizer
{
    //close both dropdownmenu if tapped outside
    [dropDownMenu1 closeAllComponentsAnimated:YES];
    [dropDownMenu2 closeAllComponentsAnimated:YES];
}

Solution for 2nd issue, using tag, and this class's provided method:

-(void) dropdownMenu:(MKDropdownMenu *)dropdownMenu didOpenComponent:(NSInteger)component
{
    if (dropdownMenu.tag == 0)
        [self.dropDownMenu1 closeAllComponentsAnimated:YES];
    else if (dropdownMenu.tag == 1)
        [self.dropDownMenu2 closeAllComponentsAnimated:YES];
}

Thank you so much!

maxkonovalov commented 7 years ago

You are welcome :)