Question

In my application I'm displaying the UIView as a popup when user click the button now the problem is it's not dismissing when click somewhere in the application please tell me how to dismiss the UIView popup.

Here is the code which user for popup.

- (void) showPopView
{
   self.popview.alpha = 1;
   [self.popview setFrame:CGRectMake(15, 100, 300, 300)];
   //[self dismissPopoverAnimated:NO];
}

Popup Button code.

- (IBAction)click:(id)sender {
   [self showPopView1];
}

In viewDidLoad i have used this code.

self.popview.alpha = 0;

The above code i have used to display UIView as a popup please tell how to dismiss the popup when user click outside.

Thanks.

Was it helpful?

Solution

What i would do is add a touchable overlay behind your popup.

In your .h

@interface YourController : UIViewController{
    UIView *overlay;
}

in your view did load

overlay = [[UIView alloc] initWithFrame:self.view.frame];
overlay.bakcgroundColor = [UIColor clearColor];
UITapGestureRecognizer *singleFingerTap = 
[[UITapGestureRecognizer alloc] initWithTarget:self 
                                      action:@selector(handleSingleTap)];
[overlay addGestureRecognizer:singleFingerTap];

And then your methods would look like :

- (void) showPopView
{
   [self.view addSubview:overlay];
   self.popview.alpha = 1;
   [self.popview setFrame:CGRectMake(15, 100, 300, 300)];
   //[self dismissPopoverAnimated:NO];
}

- (void)handleSingleTap{
    [overlay removeFromSuperview];
    self.popview.alpha = 0;
    [self.popview setFrame:CGRectZero];
}

OTHER TIPS

In background of pop up view add custom button(UIButton) to hide the popup. As it is custom button user can see the background view. Make sure button should occupy whole screen. Also when u show the pop view show the button and when user hide the pop view hide the button also so that user can get access to all area. This is the most simplest way. Other options are there like Tap gesture or check for the touches but custom button in background can minimize the risk.

I did created a demo using UIButton and it's working ,check below-

- (void)viewDidLoad
{
 [super viewDidLoad];
 backgroundButton = [[UIButton alloc] initWithFrame:CGRectMake(0,0,self.view.frame.size.width,self.view.frame.size.height)];

 [backgroundButton addTarget:self action:@selector(tapDetected) forControlEvents:UIControlEventTouchUpInside];
}

-(void)tapDetected
{
 [backgroundButton removeFromSuperview];
 [tempView removeFromSuperview];
}

-(void)showPopup /* on button click I created popup view as you already had */
{
  [self.view addSubview:backgroundButton]; //Adding button to self.view

 tempView = [[UIView alloc] initWithFrame:CGRectMake(15, 100, 300, 300)];
 [tempView setBackgroundColor:[UIColor redColor]];

 [backgroundButton addSubview:tempView];  //Adding popup view to button.
 [tempView setAlpha:1];
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top