如果点击iOS屏幕上的其他位置,则会关闭菜单?

jas*_*san 4 github ios uitapgesturerecognizer

所以我从github 使用这个菜单.目前,如果再次单击"点击"按钮,菜单会打开并缩回,但如果用户点击除按钮之外的屏幕上的任何其他位置,我还希望菜单缩进.我遇到的问题是我在带有tabbarcontroller的导航栏中实现这个问题,如果我点击按钮打开菜单然后单击不同的选项卡而不折叠气泡菜单会发生什么.然后,如果我回到相同的选项卡,泡泡菜单在视觉上仍然打开但在代码中它仍然认为它已折叠,这导致添加另一个子视图的任何建议的奇怪行为?

以下是它现在如何工作的示例.这是该守则链接. 在此输入图像描述

Fly*_*ast 5

有两种方法:

第一种方法:

您可以为按钮和其他视图设置一个标签,这些视图不希望在敲击菜单时将其关闭:

button.tag=99;
button2.tag=99;
backgroundImage.tag=99;
Run Code Online (Sandbox Code Playgroud)

然后在viewcontroller中,使用touchesBegan:withEvent:委托

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


    UITouch *touch = [touches anyObject];

    if(touch.view.tag!=99){
        //Call your dismiss method
    }

}
Run Code Online (Sandbox Code Playgroud)

第二种方法:

如果您的按钮有一个叠加层(例如,突出显示按钮的背景,并填满整个视图),您可以添加一个UITapGestureRecognizer,并在每次希望显示自定义视图时将其添加到视图中.这是一个例子:

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];

}
Run Code Online (Sandbox Code Playgroud)

对于类似的案例,你可以在这里看到我的答案.