最近接到一个需求,是要记录一个TextView中手指滑动时候的接触屏幕的起始和终点坐标(相对于屏幕的),同时记录滑动时间。
查了挺多资料,好像都不能完美达到需求的目标,最后用以下代码完美解决:
首先我们知道TextView是ScrollView的子类,那么我们遵循了UITextViewDelegate后,会有以下方法:
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView; //滑动即将开始时触发
- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset; //手指滑动离开时触发
有了以上两个方法,那接下来我们就需要在这两个方法里面获取到Touch的坐标:
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
//获取滑动手势
switch (scrollView.panGestureRecognizer.state) {
//当手势识别为开始滑动时
case UIGestureRecognizerStateBegan:
{
//locationInView这个方法很重要,它是UIGestureRecognizer的实例方法,这里UIPanGestureRecognizer是它的子类
CGPoint point = [scrollView.panGestureRecognizer locationInView:self.view];
self.startX = [NSString stringWithFormat:@"%0.f",point.x]; //我这里取整数
self.startY = [NSString stringWithFormat:@"%0.f",point.y];
NSLog(@"startX:%@, startY:%@", _startX, _startY);
self.startTime = [NSDate date];
break;
}
default:
break;
}
}
- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset{
switch (scrollView.panGestureRecognizer.state) {
case UIGestureRecognizerStateEnded:
{
CGPoint point = [scrollView.panGestureRecognizer locationInView:self.view];
NSString *endX = [NSString stringWithFormat:@"%0.f",point.x];
NSString *endY = [NSString stringWithFormat:@"%0.f",point.y];
NSLog(@"endX:%@, endY:%@", endX, endY);
NSString *duration = [NSString stringWithFormat:@"%0.lf",[[NSDate date] timeIntervalSinceDate:self.startTime] * 1000];
NSLog(@"duration: %@",duration);
}
break;
default:
break;
}
}
以上就是完美的解决方法了,代码不难,就只是要熟悉scrollView的代理方法和手势,希望能帮助到你们,求点赞投币哈哈哈