UIResponder 这个类定义了很多用来处理响应和时间处理的类。他的子类有UIApplication,UIView以及UIWindow等。
IOS中分为两类事件:触摸事件,和移动事件。最原始的事件处理方是touchesBegan:withEvent:
,touchesMoved:withEvent:
, touchesEnded:withEvent:
, and touchesCancelled:withEvent:。
无论任何时候手指只要触摸屏幕或是在屏幕上移动拖拽甚至离开屏幕都会导致一个UIEvent对象产生。
在UIResponder中有一个非常重要的概念叫做Responder Chain,个人的理解是这是按照一定规则组织的响应、处理事件的一条链表。在了解UIResponder之前还得在了解一个概念Hit-Testing。在IOS中通常使用hit-testing去找到那个被触摸的视图。这个视图叫hit-test view,当IOS找到hit-test view后就把touch event交个那个视图来处理。下面画个图来说明一下,当点击视图E时看一下hit-testing的工作过程。
1.确定改触摸事件发生在view A范围内,接下来测试view B以及view C。
2.检查发现事件不再view B范围内发生,接下来检查view C发现触摸事件发生在了view C中,所以检查 view D,view E。
3.最后发现事件发生在view E的范围内所以view E成为了hit-test view。
下面是关于调用hit-test的官方说明:
The hitTest:withEvent:
method returns the hit test view for a given CGPoint
and UIEvent
. The hitTest:withEvent:
method begins by calling thepointInside:withEvent:
method on itself. If the point passed into hitTest:withEvent:
is inside the bounds of the view, pointInside:withEvent:
returns YES
. Then, the method recursively calls hitTest:withEvent:
on every subview that returns YES
.
canBecomeFirstResponder
方法让他返回YES
/*PMBViewController*/
#import "PMBViewController.h"
#import "PMBViewOne.h"
#import "PMBVIewTwo.h"
#import "PMBVIewThree.h"
@interface PMBViewController ()
@property (weak, nonatomic) IBOutlet PMBVIewThree *viewThree;
@property (weak, nonatomic) IBOutlet PMBVIewTwo *viewTwo;
@property (weak, nonatomic) IBOutlet PMBViewOne *viewOne;
@end
@implementation PMBViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
/*PMBViewOne*/
#import "PMBViewOne.h"
@implementation PMBViewOne
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
[super touchesBegan:touches withEvent:event];
[[[touches anyObject] view] setBackgroundColor:[UIColor redColor]];
}
@end
/*PMBVIewTwo*/
#import "PMBVIewTwo.h"
@implementation PMBVIewTwo
@end
/*PMBVIewThree*/
#import "PMBVIewThree.h"
@implementation PMBVIewThree
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
[super touchesBegan:touches withEvent:event];
[[[touches anyObject] view] setBackgroundColor:[UIColor greenColor]];
}
@end