1. UIResponder基本介紹
- 父類是NSObject
- UIView事件處理包括
- 觸摸事件處理
- 加速計事件處理
- 遠程控制事件處理
2. UIView的觸摸事件處理(誰是響應者,誰調用)
//手指開始觸摸view時,系統自動調用
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
//手指在view上移動,系統自動調用(隨著手指的移動,會持續調用該方法)
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
//手指離開view,系統自動調用
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
//觸摸結束前,某個系統事件(例如電話呼入)會打斷觸摸過程,系統自動調用
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
//提示:touches中存放的都是UITouch對象
3. UIView的觸摸系列方法touches和event參數
-
一次完整的觸摸過程,會經歷3個狀態:
- 觸摸開始:
- (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
- 觸摸開始:
-
4個觸摸事件處理方法中,都有NSSet *touches和UIEvent *event兩個參數
- event參數:一次完整的觸摸過程中,只會產生一個事件對象,4個觸摸方法都是同一個event參數
-
touches參數(根據touches中UITouch的個數可以判斷出是單點觸摸還是多點觸摸):
- 如果兩根手指同時觸摸一個view,那么view只會調用一次touchesBegan:withEvent:方法,touches參數中裝著2個UITouch對象
- 如果這兩根手指一前一后分開觸摸同一個view,那么view會分別調用2次touchesBegan:withEvent:方法,并且每次調用時的touches參數中只包含一個UITouch對象
4. UIView的加速計事件處理
- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event;
- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event;
- (void)motionCancelled:(UIEventSubtype)motion withEvent:(UIEvent *)event;
5. UIView的遠程控制事件處理
- (void)remoteControlReceivedWithEvent:(UIEvent *)event;
6. 應用實例——手指拖動時,控件跟隨拖動實現
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
##拖動位移效果
// 拿到UITouch就能獲取當前點
UITouch *touch = [touches anyObject];
// 獲取當前點
CGPoint curP = [touch locationInView:self];
// 獲取上一個點
CGPoint preP = [touch previousLocationInView:self];
// 獲取手指x軸偏移量
CGFloat offsetX = curP.x - preP.x;
// 獲取手指y軸偏移量
CGFloat offsetY = curP.y - preP.y;
// 移動當前view
self.transform = CGAffineTransformTranslate(self.transform, offsetX, offsetY);
}