触摸事件的传递
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了触摸事件的传递相关的知识,希望对你有一定的参考价值。
提示:UIImageView的userInteractionEnabled 默认就是NO,因此UIImageView以及它的子控件默认是不能接触事件的
Main.storyboard
ViewController.m
//
// ViewController.m
// 7A02.触摸事件的传递
//
// Created by huan on 16/2/3.
// Copyright © 2016年 huanxi. All rights reserved.
//
#import "ViewController.h"
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIImageView *imageView;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
//当父控件不能接收触摸事件的时候,它的子控制件不在遍历
//当触摸点不在父控件的事件,它的子控件也不在遍历
//往图片添加一个按钮
UIButton *btn = [UIButton buttonWithType:UIButtonTypeContactAdd];
[btn addTarget:self action:@selector(btnClick) forControlEvents:UIControlEventTouchUpInside];
[self.imageView addSubview:btn];
}
-(void)btnClick{
NSLog(@"%s", __func__);
}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
NSLog(@"%s %p", __func__, event);
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
CZWhiteView.m(控制器的view)
#import "CZWhiteView.h"
@implementation CZWhiteView
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
NSLog(@"%s %p", __func__, event);
}
@end
CZRedView.m
#import "CZRedView.h"
@implementation CZRedView
/**
* 不实现touchesBegan方法,默认把事件传给上一个响应者(接收事件,不处理,交给上一个响应者)
*/
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
NSLog(@"%s, %p", __func__, event);
//调用了super 方法,相当于把事件传给上一个响应者
[super touchesBegan:touches withEvent:event];
}
@end
CZGreen.m
#import "CZGreenView.h"
@implementation CZGreenView
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
NSLog(@"%s", __func__);
}
#pragma mark 判断当前的触摸点在不在自己的身上
-(BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event{
//绿色左边的可以“响应事件”,右边不可以响应事件
if (point.x <= self.bounds.size.width * 0.5) {
return YES;
}
// BOOL pointInside = [super pointInside:point withEvent:event];
// NSLog(@"%s %d", __func__, pointInside);
// return pointInside;
return NO;
}
@end
CZBlue.m
#import "CZBlueView.h"
@implementation CZBlueView
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
NSLog(@"%s", __func__);
}
@end
以上是关于触摸事件的传递的主要内容,如果未能解决你的问题,请参考以下文章
安卓编程问题。怎么让悬浮窗中的view不拦截触摸事件,并将触摸事件传递给手机桌面?
Android 事件分发事件分发源码分析 ( Activity 中各层级的事件传递 | Activity -> PhoneWindow -> DecorView -> ViewGroup )(代码片段