3

嗨,我想获取任何控件的触摸位置/点或发生触摸的任何位置。

为此,我已经实现了这一点,但我没有得到正确的接触点。

   // Create gesture recognizer, notice the selector method
UITapGestureRecognizer *oneFingerTwoTaps =
[[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(oneFingerTwoTaps)] autorelease];
oneFingerTwoTaps.delegate=self;
// Set required taps and number of touches
[oneFingerTwoTaps setNumberOfTapsRequired:1];
[oneFingerTwoTaps setNumberOfTouchesRequired:1];
[[self view] addGestureRecognizer:oneFingerTwoTaps];

 - (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {

    CGPoint point= [touch locationInView:touch.view];
        NSLog(@"Point - %f, %f",point.x,point.y);
    NSLog(@"Touch");
    return NO; // handle the touch
}

当我试图点击任何 UIButton、UIImage、UITableView 时,它没有给我正确的点击点,我做错了什么吗?请帮我。谢谢你。

4

2 回答 2

8

您的代码在视图中打印触摸的位置。因此,如果您在中间触摸一个 50x100 大小的按钮,它将打印“Point 25.0, 50.0”。

如果要查找 UIScreen 的触摸位置,则必须转换值:

 - (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {

    CGPoint point = [touch locationInView:touch.view];
    CGPoint pointOnScreen = [touch.view convertPoint:point toView:nil];
    NSLog(@"Point - %f, %f", pointOnScreen.x, pointOnScreen.y);
    NSLog(@"Touch");
    return NO; // handle the touch
}

或者直接获取窗口(屏幕)空间中的坐标:

 - (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {

    CGPoint pointOnScreen = [touch locationInView:nil];
    NSLog(@"Point - %f, %f", pointOnScreen.x, pointOnScreen.y);
    NSLog(@"Touch");
    return NO; // handle the touch
}
于 2013-06-14T13:54:01.077 回答
0

这是@DrummerB 答案的快速版本。

// add as property
var tapRecognizer: UIGestureRecognizer! 

// add in viewDidLoad() 
tapRecognizer = UIGestureRecognizer()
tapRecognizer.delegate = self // inherit UIGestureRecognizerDelegate
self.view.addGestureRecognizer(tapRecognizer)

// listen for delegate method
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
        let pointOnScreen: CGPoint = touch.location(in: nil)
        print("Point - \(pointOnScreen.x), \(pointOnScreen.y)")
        print("Touch")
        return false
}

// 这对我有用。xcode 9.2,iOS 11.2

于 2018-01-09T11:18:30.180 回答