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

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];
}
It works 100%
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
[super touchesBegan:touches withEvent:event];
[urView removeFromSuperview];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With