如何从挖掘位置获取CGPoint?

我正在为iPaddevise一个graphics计算器应用程序,我想添加一个function,用户可以在graphics视图中点击一个区域,使文本框popup,显示它们所触摸的点的坐标。 我怎样才能从这个CGPoint?

你有两条路

1。

-(void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { UITouch *touch = [[event allTouches] anyObject]; CGPoint location = [touch locationInView:touch.view]; } 

在这里,你可以从当前视图中获取点的位置…

2。

 UITapGestureRecognizer *tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapped:)]; [tapRecognizer setNumberOfTapsRequired:1]; [tapRecognizer setDelegate:self]; [self.view addGestureRecognizer:tapRecognizer]; 

在这里,当你想用你的主视图的子对象或子视图做这个代码的时候使用这个代码

尝试这个

 - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { UITouch *touch = [touches anyObject]; // Get the specific point that was touched CGPoint point = [touch locationInView:self.view]; NSLog(@"X location: %f", point.x); NSLog(@"Y Location: %f",point.y); } 

你可以使用“touchesEnded”,如果你想看看用户把手指从屏幕上取下的地方,而不是他们触摸的地方。

在地图视图中使用UIGestureRecognizer可能会更好也更简单,而不是尝试子类化和手动拦截触摸。

步骤1:首先,将手势识别器添加到地图视图中:

  UITapGestureRecognizer *tgr = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGestureHandler:)]; tgr.delegate = self; //also add <UIGestureRecognizerDelegate> to @interface [mapView addGestureRecognizer:tgr]; 

步骤2:接下来,执行器应该同时识别带有testing识别器并返回YES,以便您的轻击手势识别器可以与地图同时工作(否则,在引脚上轻拍不会被地图自动处理):

 - (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer :(UIGestureRecognizer *)otherGestureRecognizer { return YES; } 

第3步:最后,实施手势处理程序:

 - (void)tapGestureHandler:(UITapGestureRecognizer *)tgr { CGPoint touchPoint = [tgr locationInView:mapView]; CLLocationCoordinate2D touchMapCoordinate = [mapView convertPoint:touchPoint toCoordinateFromView:mapView]; NSLog(@"tapGestureHandler: touchMapCoordinate = %f,%f", touchMapCoordinate.latitude, touchMapCoordinate.longitude); } 

如果使用UIGestureRecognizerUITouch对象,则可以使用locationInView:方法在用户触摸的给定视图内检索CGPoint

只是想折腾Swift 4的答案,因为API是非常不同的期待。

 override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { if let touch = event?.allTouches?.first { let loc:CGPoint = touch.location(in: touch.view) //insert your touch based code here } } 

要么

 let tapGR = UITapGestureRecognizer(target: self, action: #selector(tapped)) view.addGestureRecognizer(tapGR) @objc func tapped(gr:UITapGestureRecognizer) { let loc:CGPoint = gr.location(in: gr.view) //insert your touch based code here } 

在这两种情况下, loc将包含视图中所触及的点。

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