首页 > 技术文章 > 如何让触摸事件穿透一个View

YouXianMing 2014-10-23 21:24 原文

如何让触摸事件穿透一个View

偶然间发现,如何屏蔽或者让触摸事件穿透一个view是一个很简单的事情。

现象:

源码:

//
//  ViewController.m
//  UserInteraction
//
//  Created by YouXianMing on 14/10/23.
//  Copyright (c) 2014年 YouXianMing. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    // 新建按钮
    UIButton *button = [[UIButton alloc] initWithFrame:self.view.bounds];
    [button addTarget:self
               action:@selector(buttonEvent:)
     forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
    
    // 覆盖在上层的view
    UIView *testView = [[UIView alloc] initWithFrame:self.view.bounds];
    [self.view addSubview:testView];
    testView.userInteractionEnabled = YES;
}

- (void)buttonEvent:(UIButton *)button {
    NSLog(@"触摸事件");
}

@end

其实原理很简单,一个触摸事件时候被view接受或者屏蔽,完全由这个参数决定,那就是userInteractionEnabled。

所以,当你想屏蔽掉一个事件不让他穿透,设置覆盖的view的userInteractionEnabled为NO即可。

 

推荐阅读