我正在开发一个以编程方式创建弹出 View 的应用程序。现在的要求是,当用户点击该 popview 以外的其他地方时,我想从 superview 中删除该 View 。
下面是我创建 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];
}
这是我的 View 截图
最佳答案
全局声明UIView *cv
和Remove
功能一样
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[cv setHidden:YES];
[self.view.superview endEditing:YES];
}
选择 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]];
}
在你的按钮操作中
- (IBAction)Morebtn:(id)sender {
[self.view addSubview:cv];
}
关于ios - 如何在用户点击 iPhone 屏幕的任何部分时关闭以编程方式创建的 UIView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27521806/