如何获得手指坐标

时间:2012-11-14 10:39:59

标签: iphone objective-c xcode

我无法在Xcode中找到如何在iphone上获取鼠标/手指的坐标。

我试过了:

NSPoint mouseLoc;
mouseLoc = [NSEvent mouseLocation];

但这似乎不适用于iPhone? API无法识别它。

有没有人知道这样做的方法?

3 个答案:

答案 0 :(得分:4)

以下是Apple的文档:UIResponder Class Reference。在UIViewUIViewController的子类中,您可以添加此方法:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touched = [[event allTouches] anyObject];
    CGPoint location = [touch locationInView:touched.view];
    NSLog(@"x=%.2f y=%.2f", location.x, location.y);
}

答案 1 :(得分:2)

你正在使用可可类。对于iPhone,有cocoa.touch,你需要它的类UIEvent。
方法allTouches返回窗口的所有触摸事件。一旦触摸,您可以询问它在视图中的位置。

示例:

void event : (UIEvent*) event
{
    NSSet* touches=[event allTouches];
    for(UITouch* touch in touches)
    {
        CGPoint point=[touch locationInView: yourView];
        <Do what you need to do with the point>
    }
}

答案 2 :(得分:1)

您可以使用UITapGestureRecognizer识别手指触摸屏幕的位置。为此,您必须在控件上添加一个UITapGestureRecognizer对象/出口,例如在我的示例中,我在View上添加UITapGestureRecognizer。

    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(fingerTappedHere:)];
tapGesture.numberOfTapsRequired = 1;
tapGesture.numberOfTouchesRequired = 1;
[self.view addGestureRecognizer:tapGesture];
self.view.userInteractionEnabled = YES;


- (void)fingerTappedHere:(UITapGestureRecognizer *)sender {

CGPoint touchedPoint = [sender locationInView:self.view];
NSLog(@"x = %f, y = %f", touchedPoint.x, touchedPoint.y);

}

希望它会对你有所帮助。如需进一步查询,请通过sales@agicent.com与我们联系。我们会尽力解决。