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

9
我该如何获取UIView中手指点击的坐标?(我不想使用大量按钮的数组)
谢谢。
6个回答

38

有两种方法可以实现这个功能。如果你已经有了一个正在使用的 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
}
如果您还没有继承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
    }
}

1
touchesEnded:withEvent: 也可以从 UIViewController 中使用,因为它也是从 UIResponder 派生而来的。 - taskinoor

4

Swift 3的答案

let tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.tapAction(_:)))
yourView.addGestureRecognizer(tapGesture)


func tapAction(_ sender: UITapGestureRecognizer) {

      let point = sender.location(in: yourView)


}

3

我猜你是指识别手势(和触摸)。寻找如此广泛的问题的最佳起点是苹果的示例代码Touches。它详细介绍了大量信息。


2
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [touches anyObject];
    CGPoint touchPoint = [touch locationInView:myView];
    NSLog("%lf %lf", touchPoint.x, touchPoint.y);
}

您需要这样做。 touchesBegan:withEvent:UIResponder的一个方法,从中派生了UIViewUIViewController。如果您搜索此方法,则会找到几个教程。苹果公司的MoveMe示例是一个不错的选择。


2
func handleFrontTap(gestureRecognizer: UITapGestureRecognizer) {
    print("tap working")
    if gestureRecognizer.state == UIGestureRecognizerState.Recognized
    { 
      `print(gestureRecognizer.locationInView(gestureRecognizer.view))`
    }
}

0

Swift 5.6:

您可以在您的UIResponder中覆盖以下内容(UIView和UIViewController都继承自它):

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
    if let touch = touches.first {
        let point = touch.location(in: someView)
        print("x = \(point.x), y = \(point.y)")
    }
}

或者在您的手势识别处理程序中:

@objc func handleLongPress(gestureRecognizer: UILongPressGestureRecognizer) {
    let point = gestureRecognizer.location(in: someView)
    print("x = \(point.x), y = \(point.y)")

}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接