事件包括有三類(lèi):Touch Motion Remote 本篇主要介紹touch事件
Touch事件
事件產(chǎn)生->事件分發(fā)->事件響應(yīng)
每產(chǎn)生一個(gè)時(shí)間都會(huì)產(chǎn)生一個(gè)UIEvent對(duì)象,該對(duì)象記錄了事件、類(lèi)型、觸點(diǎn)等信息
@interface UIEvent:NSObject
屬性有 type,subType
方法:-(nullable NSSet<UITouch*>*)allTouches//說(shuō)明UIEvent持有UITouch,也能用以判斷是幾個(gè)點(diǎn)的觸控
@interface UITouch:NSObject
屬性 phase,tapCount,gestureRecgnizers
UIView中有方法-(UIView*)hitTest:(CGPoint)point withEvent:(UIEvent*)event//用以判斷當(dāng)前的touch是點(diǎn)在了那個(gè)View上
hitTest方法從UIWindow開(kāi)始父類(lèi)傳到子類(lèi),subViews按照逆順序遍歷
事件分發(fā)從UIAppliction一直到hitTestView
-(void)sendEvent:(UIEvent*)event;
touch響應(yīng)事件?
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent*)event
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent*)event
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent*)event
-(void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent*)event
Responder Chain從子類(lèi)到父類(lèi)傳遞 一直到AppDelegate如果都沒(méi)有響應(yīng)就丟棄
實(shí)例 加大按鈕的點(diǎn)擊區(qū)域
方法1
-(UIView*)hitTest:(CGPoint)point withEvent:(UIEvent*)event{
? ??//使用cgrectInset作用是 改變目標(biāo)frame的inset
? ? CGRect targetRect=CGRectInset(_button.frame, -ExtraPadding, -ExtraPadding);
? ? //重點(diǎn) 查看點(diǎn)擊區(qū)域在targetRect中嗎
? ? if(CGRectContainsPoint(targetRect,point)){
? ? ? ? //把這一區(qū)域設(shè)置為button的點(diǎn)擊區(qū)域
? ? ? ? return?_button;
? ? }
? ? else
? ? ? ? return?[super?hitTest:pointwithEvent:event];
}
方法二: 調(diào)用hitTest會(huì)先調(diào)用ponitInside
創(chuàng)建button類(lèi) 重寫(xiě)
-(BOOL)pointInside:(CGPoint)point withEvent:(UIEvent*)event{
? ? CGRecttargetRect=CGRectInset(self.bounds,-20, -20);
? ? //如果想使用frame 因?yàn)閒rame是父view的坐標(biāo)系 所以需要轉(zhuǎn)化
? ? //CGPoint convertPoint=[self convertPoint:point toView:self.superview];
? ? //CGRect targetRectFrame=CGRectInset(self.frame, -20, -20);
? ? //此時(shí)下方的point應(yīng)該使用convertPoint
? ? if(CGRectContainsPoint(targetRect, point)){
? ? ? ? return??YES;
? ? }
? ? else
? ? return? [super?pointInside:pointwithEvent:event];
子View超過(guò)了父View的范圍
方法修改父View的pointInside
-(BOOL)pointInside:(CGPoint)point withEvent:(UIEvent*)event
{
? ? //ponit應(yīng)該是button的坐標(biāo)系中 而此時(shí)point是view的 因此需要轉(zhuǎn)化?
? ? if([_button pointInside:[self convertPoint:point toView:_button] withEvent:event])
? ? {
? ? ? ? return?YES;
? ? }
? ? else
? ? ? return? [super?pointInside:pointwithEvent:event];
}