问题描述
我有一个 UIView,当点击按钮时会出现它,我基本上将它用作自定义警报视图.现在,当用户在我添加到主视图的自定义 UIView 之外点击时,我想隐藏自定义视图,我可以使用 customView.hidden = YES;
轻松做到这一点,但我如何检查视图外的水龙头?
I have a UIView, that I have appear when a button is tapped, I am using it as a custom alert view essentially. Now when the user taps outside the custom UIView that I added to the main view, I want to hide the cusomt view, I can easily do this with customView.hidden = YES;
but how can I check for the tap outside the view?
感谢您的帮助
推荐答案
有两种方法
第一种方法
您可以为自定义视图设置标签:
You can set a tag for your custom view:
customview.tag=99;
然后在您的视图控制器中,使用 touchesBegan:withEvent:
委托
An then in your viewcontroller, use the touchesBegan:withEvent:
delegate
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
UITouch *touch = [touches anyObject];
if(touch.view.tag!=99){
customview.hidden=YES;
}
}
第二种方法
更有可能的是,每次你想弹出一个自定义视图时,它背后都有一个覆盖层,它会填满你的屏幕(例如,alpha ~0.4 的黑色视图).在这些情况下,您可以向其添加 UITapGestureRecognizer
,并在每次希望显示自定义视图时将其添加到您的视图中.举个例子:
It's more likely that every time you want to popup a custom view, there's an overlay behind it, which will fill your screen (e.g. a black view with alpha ~0.4). In these cases, you can add an UITapGestureRecognizer
to it, and add it to your view every time you want your custom view to show up. Here's an example:
UIView *overlay;
-(void)addOverlay{
overlay = [[UIView alloc] initWithFrame:CGRectMake(0, 0,self.view.frame.size.width, self.view.frame.size.height)];
[overlay setBackgroundColor:[UIColor colorWithRed:0 green:0 blue:0 alpha:0.5]];
UITapGestureRecognizer *overlayTap =
[[UITapGestureRecognizer alloc] initWithTarget:self
action:@selector(onOverlayTapped)];
[overlay addGestureRecognizer:overlayTap];
[self.view addSubview:overlay];
}
- (void)onOverlayTapped
{
NSLog(@"Overlay tapped");
//Animate the hide effect, you can also simply use customview.hidden=YES;
[UIView animateWithDuration:0.2f animations:^{
overlay.alpha=0;
customview.alpha=0;
}completion:^(BOOL finished) {
[overlay removeFromSuperview];
}];
}
这篇关于在外面点击时删除视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!