是否可以获得触摸的x和y坐标?如果是这样,请有人提供一个非常简单的示例,其中坐标刚刚记录到控制台。
答案 0 :(得分:14)
使用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:
方法
- (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);
}
答案 1 :(得分:2)
首先,您需要为所需的视图添加手势识别器。
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 Class Reference
答案 2 :(得分:0)
这是一个非常基本的示例(将其置于视图控制器中):
- (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
执行此操作,这在许多情况下更实用。