UIView的觸摸事件處理
UIView是UIResponder的子類,可以覆蓋下列4個方法處理不同的觸摸事件
一根或者多根手指開始觸摸view,系統(tǒng)會自動調(diào)用view的下面方法
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
一根或者多根手指在view上移動,系統(tǒng)會自動調(diào)用view的下面方法(隨著手指的移動,會持續(xù)調(diào)用該方法)
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
一根或者多根手指離開view,系統(tǒng)會自動調(diào)用view的下面方法
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
觸摸結(jié)束前,某個系統(tǒng)事件(例如電話呼入)會打斷觸摸過程,系統(tǒng)會自動調(diào)用view的下面方法
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
提示:touches中存放的都是UITouch對象
UITouch是什么
當用戶用一根手指觸摸屏幕時,會創(chuàng)建一個與手指相關(guān)聯(lián)的UITouch對象
一根手指對應一個UITouch對象
UITouch的作用
保存著跟手指相關(guān)的信息,比如觸摸的位置、時間、階段
當手指移動時,系統(tǒng)會更新同一個UITouch對象,使之能夠一直保存該手指在的觸摸位置
當手指離開屏幕時,系統(tǒng)會銷毀相應的UITouch對象
提示:iPhone開發(fā)中,要避免使用雙擊事件!
UITouch的屬性
觸摸產(chǎn)生時所處的窗口
@property(nonatomic,readonly,retain) UIWindow *window;
觸摸產(chǎn)生時所處的視圖
@property(nonatomic,readonly,retain) UIView *view;
短時間內(nèi)點按屏幕的次數(shù),可以根據(jù)tapCount判斷單擊、雙擊或更多的點擊
@property(nonatomic,readonly) NSUInteger tapCount;
記錄了觸摸事件產(chǎn)生或變化時的時間,單位是秒
@property(nonatomic,readonly) NSTimeInterval timestamp;
當前觸摸事件所處的狀態(tài)
@property(nonatomic,readonly) UITouchPhase phase;
UITouch的方法
- (CGPoint)locationInView:(UIView *)view;
返回值表示觸摸在view上的位置
這里返回的位置是針對view的坐標系的(以view的左上角為原點(0, 0))
調(diào)用時傳入的view參數(shù)為nil的話,返回的是觸摸點在UIWindow的位置
- (CGPoint)previousLocationInView:(UIView *)view;
該方法記錄了前一個觸摸點的位置
UIEvent是什么
每產(chǎn)生一個事件,就會產(chǎn)生一個UIEvent對象
UIEvent:稱為事件對象,記錄事件產(chǎn)生的時刻和類型
常見屬性
事件類型
@property(nonatomic,readonly) UIEventType type;
@property(nonatomic,readonly) UIEventSubtype subtype;
事件產(chǎn)生的時間
@property(nonatomic,readonly) NSTimeInterval timestamp;
UIEvent還提供了相應的方法可以獲得在某個view上面的觸摸對象(UITouch)
touches和event參數(shù)
一次完整的觸摸過程,會經(jīng)歷3個狀態(tài):
觸摸開始:
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
觸摸移動:
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
觸摸結(jié)束:
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
觸摸取消(可能會經(jīng)歷):
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
4個觸摸事件處理方法中,都有NSSet *touches和UIEvent *event兩個參數(shù)
一次完整的觸摸過程中,只會產(chǎn)生一個事件對象,4個觸摸方法都是同一個event參數(shù)
如果兩根手指同時觸摸一個view,那么view只會調(diào)用一次touchesBegan:withEvent:方法,touches參數(shù)中裝著2個UITouch對象
如果這兩根手指一前一后分開觸摸同一個view,那么view會分別調(diào)用2次touchesBegan:withEvent:方法,并且每次調(diào)用時的touches參數(shù)中只包含一個UITouch對象
根據(jù)touches中UITouch的個數(shù)可以判斷出是單點觸摸還是多點觸摸