是否可以获取触摸的x和y坐标?如果可以,能否提供一个非常简单的示例,仅将坐标记录到控制台中。
是否可以获取触摸的x和y坐标?如果可以,能否提供一个非常简单的示例,仅将坐标记录到控制台中。
使用touchesBegan事件
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [[event allTouches] anyObject];
CGPoint touchPoint = [touch locationInView:self.view];
NSLog(@"Touch x : %f y : %f", touchPoint.x, touchPoint.y);
}
当触控开始时,将触发此事件。
使用手势
在viewDidLoad:
方法中注册您的UITapGestureRecognizer。
- (void)viewDidLoad {
[super viewDidLoad];
UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGestureRecognizer:)];
[self.view setUserInteractionEnabled:YES];
[self.view addGestureRecognizer:tapGesture];
}
设置tapGestureRecognizer函数
// Tap GestureRecognizer function
- (void)tapGestureRecognizer:(UIGestureRecognizer *)recognizer {
CGPoint tappedPoint = [recognizer locationInView:self.view];
CGFloat xCoordinate = tappedPoint.x;
CGFloat yCoordinate = tappedPoint.y;
NSLog(@"Touch Using UITapGestureRecognizer x : %f y : %f", xCoordinate, yCoordinate);
}
UITapGestureRecognizer *myTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(myTapRecognizer:)];
[self.myView setUserInteractionEnabled:YES];
[self.myView addGestureRecognizer:myTap];
然后在手势识别器方法中,您调用locationInView:
- (void)myTapRecognizer:(UIGestureRecognizer *)recognizer
{
CGPoint tappedPoint = [recognizer locationInView:self.myView];
CGFloat xCoordinate = tappedPoint.x;
CGFloat yCoordinate = tappedPoint.y;
}
你可能想要看一下苹果公司的UIGestureRecognizer类参考文档
这是一个非常基本的示例(将其放置在您的视图控制器中):
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
CGPoint currentPoint = [touch locationInView:self.view];
NSLog(@"%@", NSStringFromCGPoint(currentPoint));
}
touchesBegan:withEvent:
,它在触摸开始时触发,并且touchesEnded:withEvent:
在触摸结束时触发(即手指抬起)。UIGestureRecognizer
来实现这一功能,在许多情况下更为实用。self.view
上的视图,如果没有设置.userInteractionEnabled = NO
,都会捕获触摸事件并阻止其传递到上面给出的方法。 - Ander