在手势中屏蔽响应事件继续向父视图传递

  1. 云栖社区>
  2. 博客列表>
  3. 正文

在手势中屏蔽响应事件继续向父视图传递

游贤明 2016-04-18 10:04:11 浏览1899 评论0

摘要: 在手势中屏蔽响应事件继续向父视图传递 没有屏蔽时候的现象: 屏蔽时候的现象: 源码如下(用到了上一篇教程的源码): // // ViewController.m // BackgroundView // // Created by YouXianMing on 14-10-3.

在手势中屏蔽响应事件继续向父视图传递

没有屏蔽时候的现象:

屏蔽时候的现象:

源码如下(用到了上一篇教程的源码):

//
//  ViewController.m
//  BackgroundView
//
//  Created by YouXianMing on 14-10-3.
//  Copyright (c) 2014年 YouXianMing. All rights reserved.
//

#import "ViewController.h"
#import "UIView+BackgroundView.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    // 添加手势
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self
                                                                          action:@selector(handleSingleTap:)];
    [self.view addGestureRecognizer:tap];
    
    UILabel *label      = [[UILabel alloc] initWithFrame:self.view.bounds];
    label.text          = @"Y.X. Touch Test";
    label.textAlignment = NSTextAlignmentCenter;
    label.font          = [UIFont fontWithName:@"HelveticaNeue-Thin" size:40.f];
    label.textColor     = [UIColor redColor];
    [self.view addSubview:label];
}

- (void)tapEvent:(UITapGestureRecognizer *)tap
{
    // 显示
    [self.view showBackgroundViewAndConfig:^(BackgroundView *configView) {
        configView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.6];
        configView.startDuration = 0.4f;
        configView.endDuration   = 0.4f;
    }];
    
    // 延迟3s执行
    [self performSelector:@selector(affterDelay)
               withObject:nil
               afterDelay:3.f];
}


- (void)handleSingleTap:(UIGestureRecognizer *)gestureRecognizer
{
    UIEvent *event = [[UIEvent alloc] init];
    CGPoint location = [gestureRecognizer locationInView:gestureRecognizer.view];
    
    //check actually view you hit via hitTest
    UIView *view = [gestureRecognizer.view hitTest:location withEvent:event];
    
    if ([view.gestureRecognizers containsObject:gestureRecognizer]) {
        NSLog(@"当前视图响应了事件");
        
        // 显示
        [self.view showBackgroundViewAndConfig:^(BackgroundView *configView) {
            configView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.6];
            configView.startDuration = 0.4f;
            configView.endDuration   = 0.4f;
        }];
        
        // 延迟3s执行
        [self performSelector:@selector(affterDelay)
                   withObject:nil
                   afterDelay:3.f];
    }
    else {
        NSLog(@"子视图响应了事件");
    }
}


- (void)affterDelay
{
    // 隐藏
    [self.view removeBackgroundView];
}

@end

以下是核心代码处:

解决问题的出处:

http://stackoverflow.com/questions/5222998/uigesturerecognizer-blocks-subview-for-handling-touch-events/11573711#11573711

【云栖快讯】阿里云栖开发者沙龙(Java技术专场)火热来袭!快来报名参与吧!  详情请点击

网友评论