事件分爲三類:
- 觸控事件(單點、多點觸控以及各種手勢操作)
- 傳感器事件(重力、加速度傳感器等)
- 遠程控制事件(遠程遙控iOS設備多媒體播放等)
在iOS中不是任何對象都能處理事件,只有繼承了UIResponder的對象才能接收並處理事件。我們稱之爲“響應者對象”
UIApplication、UIViewController、UIView都繼承自UIResponder,因此它們都是響應者對象,都能夠接收並處理事件
UIResponder
內部提供了以下方法來處理事件
觸摸事件
- (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;
加速計事件
- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event;
- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event;
- (void)motionCancelled:(UIEventSubtype)motion withEvent:(UIEvent *)event;
遠程控制事件
- (void)remoteControlReceivedWithEvent:(UIEvent *)event;
UIView
觸摸事件處理
UIView是UIResponder的子類,可以實現下列4個方法處理不同的觸摸事件
一根或者多根手指開始觸摸view,系統會自動調用view的下面方法
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
一根或者多根手指在view上移動,系統會自動調用view的下面方法(隨着手指的移動,會持續調用該方法)
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
一根或者多根手指離開view,系統會自動調用view的下面方法
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
觸摸結束前,某個系統事件(例如電話呼入)會打斷觸摸過程,系統會自動調用view的下面方法
(void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
提示:touches中存放的都是UITouch對象
UITouch
當用戶用一根手指觸摸屏幕時,會創建一個與手指相關聯的UITouch對象
一根手指對應一個UITouch對象
UITouch的作用
保存着跟手指相關的信息,比如觸摸的位置、時間、階段
當手指移動時,系統會更新同一個UITouch對象,使之能夠一直保存該手指的觸摸位置。
當手指離開屏幕時,系統會銷燬相應的UITouch對象
提示:iPhone開發中,要避免使用雙擊事件!
// 觸摸產生時所處的窗口
@property(nonatomic,readonly,retain) UIWindow *window;
// 觸摸產生時所處的視圖
@property(nonatomic,readonly,retain) UIView *view;
// 短時間內點按屏幕的次數,可以根據tapCount判斷單擊、雙擊或更多的點擊
@property(nonatomic,readonly) NSUInteger tapCount;
// 記錄了觸摸事件產生或變化時的時間,單位是秒
@property(nonatomic,readonly) NSTimeInterval timestamp;
// 當前觸摸事件所處的狀態
@property(nonatomic,readonly) UITouchPhase phase;
- (CGPoint)locationInView:(UIView *)view;
// 返回值表示觸摸在view上的位置
// 這裏返回的位置是針對view的座標系的(以view的左上角爲原點(0, 0))
// 調用時傳入的view參數爲nil的話,返回的是觸摸點在UIWindow的位置
- (CGPoint)previousLocationInView:(UIView *)view;
// 該方法記錄了前一個觸摸點的位置
UITouchPhase是一個枚舉類型,包含:
UITouchPhaseBegan(觸摸開始)
UITouchPhaseMoved(接觸點移動)
UITouchPhaseStationary(接觸點無移動)
UITouchPhaseEnded(觸摸結束)
UITouchPhaseCancelled(觸摸取消)