自定义弹框,点击提示框外空白区域,让弹框消失

时间:2020-12-12 20:41:14

tip:

  1. self.mainView  是提示框的全屏背景。一般是透明的黑色
  2.  self.bgImg   添加提示内容的主要view

 

方法一:正常情况下,各个页面都有touchesBegan:withEvent事件的触发。使用该方法

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    UITouch *touch = [touches anyObject];
    // 计算搜索框范围
    CGPoint touchPoint = [touch locationInView:self.mainView];
    
     NSLog(@"x = %f, y = %f", touchPoint.x, touchPoint.y);
    if (touchPoint.x > (self.bgImg.kkg_x+self.bgImg.kkg_width)&& touchPoint.x < self.bgImg.kkg_x && touchPoint.y > (self.bgImg.kkg_y+self.bgImg.kkg_height) && touchPoint.y < self.bgImg.kkg_y) {

    } else {
        [self closeAlert];
    }
}

方法二:当某个触发事件中断。 有个简单粗暴方法,就是手动添加tap

tip:1.添加代理,2.调用

  1. @interface XXXXXXXX ()<UIGestureRecognizerDelegate>

    [self addAGesutreRecognizerForMainViewView];

//MainViewView  没有点击事件
- (void)addAGesutreRecognizerForMainViewView{
    
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGesturedDetected:)]; 
    tapGesture.delegate = self;
    [self.mainView addGestureRecognizer:tapGesture];
}

- (void) tapGesturedDetected:(UITapGestureRecognizer *)recognizer{
    NSSet *touches=[[NSSet alloc]init];
    UITouch *touch = [touches anyObject];
    // 计算搜索框范围
    CGPoint touchPoint = [touch locationInView:self.mainView];
    
    NSLog(@"x = %f, y = %f", touchPoint.x, touchPoint.y);
    if (touchPoint.x > (self.bgImg.kkg_x+self.bgImg.kkg_width)&& touchPoint.x < self.bgImg.kkg_x && touchPoint.y > (self.bgImg.kkg_y+self.bgImg.kkg_height) && touchPoint.y < self.bgImg.kkg_y) {
        
    } else {
        [self closeAlert];
    }
}

说明:UIScrollView(包括它的子类 UITableView 和 UICollectionView 等)是不会响应 touchesBegan:withEvent:之类的 UIResponder的方法的。加在其上的所有视图的响应者链就断了。如果在UIScrollView其上加任何的自身不具备类似UIButton一样有目标动作机制的UIView及其子类控件的时候,这个控件也不会响应 touchesBegan:withEvent:方法。即便是设置该控件的userInteractionEnabled为YES也没用。

UIScrollView的工作原理,当手指touch的时候,UIScrollView会拦截Event,会等待一段时间,在这段时间内,如果没有手指 没有移动,当时间结束时,UIScrollView会发送tracking events到子视图上。在时间结束前,手指发生了移动,那么UIScrollView就会进行移动,从而发送tracking.

 

 

 参考博客:http://www.tuicool.com/articles/fmaMnaN 

      http://285746555.blog.51cto.com/2966432/658383