如何在UIView中获取手指敲击的坐标?

jdl*_*jdl 8 iphone coordinates

如何在UIView中获取手指敲击的坐标?(我不想使用大量的按钮)

谢谢

Noa*_*oon 33

有两种方法可以实现这一目标.如果你已经有了你正在使用的UIView的子类,你可以覆盖该-touchesEnded:withEvent:子类的方法,如下所示:

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *aTouch = [touches anyObject];
    CGPoint point = [aTouch locationInView:self];
    // point.x and point.y have the coordinates of the touch
}
Run Code Online (Sandbox Code Playgroud)

如果你还没有子类的UIView,虽然和视图由视图控制器或什么的,那么你可以使用一个UITapGestureRecognizer,像这样拥有:

// when the view's initially set up (in viewDidLoad, for example)
UITapGestureRecognizer *rec = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapRecognized:)];
[someView addGestureRecognizer:rec];
[rec release];

// elsewhere
- (void)tapRecognized:(UITapGestureRecognizer *)recognizer
{
    if(recognizer.state == UIGestureRecognizerStateRecognized)
    {
        CGPoint point = [recognizer locationInView:recognizer.view];
        // again, point.x and point.y have the coordinates
    }
}
Run Code Online (Sandbox Code Playgroud)