一根或者多根手指在view上移動,系統會自動調用view的下面方法(隨着手指的移動,會持續調用該方法)
- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event;
一根或者多根手指開始觸摸view,系統會自動調用view的下面方法
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
一根或者多根手指離開view,系統會自動調用view的下面方法
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
觸摸結束前,某個系統事件(例如電話呼入)會打斷觸摸過程,系統會自動調用view的下面方法
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
以上是UIView的觸摸事件處理的流程方法
- 下面是代碼的實現
- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
NSLog(@"%@", touches);
UITouch *touch = [touches anyObject];
//當前的point
CGPoint currentP = [touch locationInView:self];
//以前的point
CGPoint preP = [touch previousLocationInView:self];
//x軸偏移的量
CGFloat offsetX = currentP.x - preP.x;
//Y軸偏移的量
CGFloat offsetY = currentP.y - preP.y;
self.transform = CGAffineTransformTranslate(self.transform, offsetX, offsetY);
}
UITouch
當用戶的手指觸摸屏幕的時,就會創建一個UITouch對象,注:一根手指對應一個UItouch對象
-
作用
-
保存一些與手指相關的消息,比如說觸摸位置(CGPoint),時間。階段
-
當手指移動的時,系統會更新同一個UITouch對象
-
手指離開時,就會銷毀對應的UItouch
-
獲得當前的point
- (CGPoint)locationInView:(nullable UIView *)view;
- 獲得前一個位置的point
- (CGPoint)locationInView:(nullable UIView *)view;
然后計算出X軸,Y軸的偏移量
- transform 在OC中,通過transform屬性可以修改對象的平移、縮放比例和旋轉角度
- 常用的創建transform結構體方法分兩大類
-
創建“基於控件初始位置”的形變
CGAffineTransformMakeTranslation(平移)
CGAffineTransformMakeScale(縮放)
CGAffineTransformMakeRotation(旋轉)
-
創建“基於transform參數”的形變
CGAffineTransformTranslate
CGAffineTransformScale
CGAffineTransformRotate