UITouch触摸事件拖动View移动的方法

UITouch触摸事件拖动View移动的方法


/**
*  触摸事件开始(手指触摸到屏幕)
*/
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
NSLog(@"%s", __func__);
}

/**
*  触摸移动时调用(手指在屏幕上移动)
*/
- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
// 1.获取UITouch对象
UITouch *touch = [touches anyObject];

UIView *view = [touch view];

//    [UIApplication sharedApplication].keyWindow
// 2.获取当前手指点的位置
CGPoint currentPoint = [touch locationInView: [UIApplication sharedApplication].keyWindow];

// 3.获取上一个手指点的位置
CGPoint previouPoint = [touch previousLocationInView: [UIApplication sharedApplication].keyWindow];

// 4.算出2次移动的偏移量
CGFloat offsetX = currentPoint.x - previouPoint.x;
CGFloat offsetY = currentPoint.y - previouPoint.y;

// 5.移动UIView视图的位置
view.transform = CGAffineTransformTranslate(view.transform, offsetX, offsetY);

NSLog(@"%s", __func__);
}

/**
*  触摸完成时调用(手指抬起)
*/
- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
NSLog(@"%s", __func__);
}

/**
*  触摸取消时调用(有电话接入)
*/
- (void)touchesCancelled:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
NSLog(@"%s", __func__);
}


Loading Disqus comments...
Table of Contents