響應者鏈
首先女坑,想要理解事件的處理機制必須要知道iOS中響應者鏈填具,要明白事件是怎么傳遞的。
如上圖匆骗,假設我們點擊viewC劳景,系統(tǒng)會從頂層baseView開始尋找,發(fā)現(xiàn)點擊事件在baseView或者其子類里碉就;baseView的子類有viewA和viewB盟广,然后從viewA和viewB中尋找,發(fā)現(xiàn)點擊事件在viewB或者其子類里瓮钥;viewB的子類為viewC和viewD筋量,再從viewC和viewD中尋找,此時發(fā)現(xiàn)點擊事件在viewC中碉熄,并且viewC沒有子類桨武,所以viewC響應并處理此點擊事件,也就是hit-test view锈津。
注意點:1.如果子視圖的Frame超過父視圖的Frame玻募,那么點擊子視圖中超出的部分,不會觸發(fā)響應時間一姿。2.只有繼承于UIResponder類的對象才能處理事件七咧。例如: UIView跃惫、UIViewContronler、UIApplication等艾栋。
iOS常用事件處理包括:1.觸摸事件爆存;2.手勢識別;3.運動事件蝗砾;4.遠程控制先较。
一、觸摸事件
#pragma mark - 觸摸事件
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
//開始觸摸時執(zhí)行
}
- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
//手指在屏幕上移動時執(zhí)行悼粮,此方法在移動過程中重復調(diào)用
}
- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
//觸摸結(jié)束時執(zhí)行
}
- (void)touchesCancelled:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
//觸摸意外取消時執(zhí)行(例如:正在觸摸時打入電話等)
}
二闲勺、手勢識別
1、UITapGestureRecognizer
點按手勢
2扣猫、UIPinchGestureRecognizer
捏合手勢
3菜循、UIPanGestureRecognizer
拖動手勢
4、UISwipeGestureRecognizer
輕掃手勢
5申尤、UILongPressGestureRecognizer
長按手勢
6癌幕、UIRotationGestureRecognizer
旋轉(zhuǎn)手勢
UIGestureRecognizer
類中一些常用的屬性、方法:
屬性:
1昧穿、@property(nonatomic,readonly) UIGestureRecognizerState state;//手勢狀態(tài)
2勺远、@property(nonatomic, getter=isEnabled) BOOL enabled; // default is YES.手勢是否可用
3、@property(nullable, nonatomic,readonly) UIView *view;//觸發(fā)手勢的視圖
方法:
1时鸵、- (instancetype)initWithTarget:(nullable id)target action:(nullable SEL)action ;
2胶逢、- (void)addTarget:(id)target action:(SEL)action;
3、- (void)removeTarget:(nullable id)target action:(nullable SEL)action;
4饰潜、- (void)requireGestureRecognizerToFail:(UIGestureRecognizer *)otherGestureRecognizer;//指定一個手勢需要另一個手勢執(zhí)行失敗后才會執(zhí)行(用來解決手勢間的沖突)
5初坠、- (CGPoint)locationInView:(nullable UIView*)view;//在指定視圖中的相對位置
6、- (NSUInteger)numberOfTouches;//觸摸點的個數(shù)
7囊拜、- (CGPoint)locationOfTouch:(NSUInteger)touchIndex inView:(nullable UIView*)view;//觸摸點相對于指定視圖的位置
三、運動事件
1比搭、- (void)motionBegan:(UIEventSubtype)motion withEvent:(nullable UIEvent *)event ;
2冠跷、- (void)motionEnded:(UIEventSubtype)motion withEvent:(nullable UIEvent *)event ;
3、- (void)motionCancelled:(UIEventSubtype)motion withEvent:(nullable UIEvent *)event ;
四身诺、遠程控制
- (void)remoteControlReceivedWithEvent:(nullable UIEvent *)event;