ios - 如何在用户点击 iPhone 屏幕的任何部分时关闭以编程方式创建的 UIView

标签 ios objective-c iphone uiview

我正在开发一个以编程方式创建弹出 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 截图 enter image description here

最佳答案

全局声明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/

相关文章:

ios - 在扩展中的弱属性上添加 didSet 观察者

ios - Swift - 检查对象是否属于给定类型(类型已作为函数参数传递)

ios - 我将如何停止在我的表格 View 中重复加载图像?

ios - 不兼容的指针类型从'NSMutableArray *'分配给'NSString *'

ios - 如何在 AdMob 中添加中介网络?

iphone - 使用Button Font Awesome 图标无法正确显示?而是显示怪异的图标

iphone - 从 iPhone 浏览器启动应用程序

ios - 如何在 Xcode 注释中添加链接以打开另一个源代码文件?

iphone - 我应该在哪里删除通知观察者?

c++ - OpenCV 根据图像集检测图像