Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dismiss programmatically created UIView when user taps on any part of iPhone screen

I am working on an app where a popup view is created programatically. Now requirement is when user taps somewhere else than that popview, I want to remove that view from superview.

Below is my code for creating view

- (IBAction)Morebtn:(id)sender {
    UIView *cv = [[UIView alloc]initWithFrame:CGRectMake(200, 60, 100, 80)];
   UIButton *label1 = [[UIButton alloc]initWithFrame:CGRectMake(-50,2, 200, 30)];
    [label1 setTitle: @"My Button" forState: UIControlStateNormal];
    label1.titleLabel.font=[UIFont fontWithName:@"SegoeUI" size:12.0];
    [label1 addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];

    [cv addSubview:label1];

    UILabel *label2 = [[UILabel alloc]initWithFrame:CGRectMake(5,20, 200, 30)];
    label2.text = @"Mark as unread";
    label2.font=[UIFont fontWithName:@"SegoeUI" size:12.0];
    [cv addSubview:label2]; //add label2 to your custom view

    [cv setBackgroundColor:[UIColor grayColor]];
    [self.view addSubview:cv];
}

Here is my screen shot of view enter image description here

like image 296
Mishal Awan Avatar asked Dec 28 '25 10:12

Mishal Awan


2 Answers

declare UIView *cv in globally

and Remove function just like

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[cv setHidden:YES];
[self.view.superview endEditing:YES];
}

choice no 2

@property (strong, nonatomic) UIView * cv;

 -(void)viewDidLoad
{
[super viewDidLoad];

// here add the view

 cv = [[UIView alloc]initWithFrame:CGRectMake(200, 60, 100, 80)];
UIButton *label1 = [[UIButton alloc]initWithFrame:CGRectMake(-50,2, 200, 30)];
[label1 setTitle: @"My Button" forState: UIControlStateNormal];
label1.titleLabel.font=[UIFont fontWithName:@"SegoeUI" size:12.0];
[label1 addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];

[cv addSubview:label1];

UILabel *label2 = [[UILabel alloc]initWithFrame:CGRectMake(5,20, 200, 30)];
label2.text = @"Mark as unread";
label2.font=[UIFont fontWithName:@"SegoeUI" size:12.0];
[cv addSubview:label2]; //add label2 to your custom view

[cv setBackgroundColor:[UIColor grayColor]];

}

in your button action

- (IBAction)Morebtn:(id)sender {

   [self.view addSubview:cv];

}
like image 194
Anbu.Karthik Avatar answered Dec 31 '25 03:12

Anbu.Karthik


It works 100%

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

        [super touchesBegan:touches withEvent:event];
        [urView removeFromSuperview];
    }
like image 22
Code cracker Avatar answered Dec 31 '25 02:12

Code cracker