什么是响应者?
UIResponder。响应者类。
iOS中所有能响应事件(触摸、晃动、远程事件)的对象都是响应者。
系统定义了⼀一个抽象的⽗父类UIResponder来表⽰示响应者。其⼦子类都是响应者。
检测触碰视图
硬件检测到触摸操作,会将信息交给UIApplication,开始检测。
UIApplication -> window -> viewController -> view -> 检测所有⼦子 视图
最终确认触碰位置,完成响应者链的查询过程。
UIApplication->window- >rootViewController
viewA -> ViewB
viewC -> ViewD -> ViewE(检测到触 摸视图)
如图1-1所示:
处理触碰事件
检测到响应者后,实现touchesBegan:withEvent:等⽅方法,即处理事 件。
如果响应者没有处理事件,事件会向下传递。如果没有响应者处理,
则丢弃触摸事件。
事件处理的顺序与触摸检测查询相反。
触摸的⼦子视图 -> view -> viewController -> window -> UIApplication
查询与处理可能会出现在面试题中.
阻断响应者链:
响应者链可以被打断。⽆无法完成检测查询过程。
视图类的属性 : userInteractionEnabled。关闭后能阻断查询过 程。
代码展示
#ResponderView.h
#import <UIKit/UIKit.h>
@interface ResponderView : UIView
@property(nonatomic,retain,readonly)UILabel *label;
@property(nonatomic,retain,readonly)UIButton *button;
@end
#ResponderView.m
#import "ResponderView.h"
@implementation ResponderView
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
// Drawing code
}
*/
- (void)dealloc
{
[_label release];
[super dealloc];
}
- (instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
_label = [[UILabel alloc]initWithFrame:CGRectMake(30, 30, 200, 100)];
[self addSubview:_label];
_button = [UIButton buttonWithType:(UIButtonTypeSystem)];
_button.frame = CGRectMake(10, 10, 100, 30);
[_label addSubview:_button];
}
return self;
}
@end
#ResponderViewController.m
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
// 在label上创建一个button,在button添加事件
ResponderView *responderView = [[ResponderView alloc]initWithFrame:[[UIScreen mainScreen]bounds]];
self.view = responderView;
responderView.label.text = @"哈哈";
responderView.label.backgroundColor = [UIColor lightGrayColor]; // xcode8的一个bug
// 在UI中,基本上所有的控件的用户交互都是打开的 但是也有一些特例 例如label,imageView
// userInteractionEnabled这个属性影响了响应者链的检测过程 所以如果将一个button放在一个label或者是imageView上 都需要将;label或者是imageView的用户交互打开才可以 否则在检测的过程中是检测不到label或者imageView上的子视图的
responderView.label.userInteractionEnabled = YES;
[responderView.button setTitle:@"点击" forState:(UIControlStateNormal)];
responderView.button.backgroundColor = [UIColor whiteColor];
[responderView.button addTarget:self action:@selector(click) forControlEvents:UIControlEventTouchUpInside];
// label的userInteractionEnabled默认是关闭的(用户交互)
[responderView release];
}
- (void)click
{
NSLog(@"哈哈");
}