如何从tapped位置获取CGPoint?

jko*_*ber 28 xcode touch ipad cgpoint ios

我正在为iPad制作一个图形计算器应用程序,我想添加一个功能,用户可以在图表视图中点击一个区域,弹出一个文本框,显示他们触摸的点的坐标.我如何从中获得CGPoint?

Par*_*shi 47

你有两种方式......

1.

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

在这里,您可以从当前视图获取位置...

2.

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

在这里,当您想要使用主视图或主视图的子视图做某事时,此代码使用


Dim*_*ima 20

试试这个

- (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);

}
Run Code Online (Sandbox Code Playgroud)

你可以使用"touchesEnded",如果你更愿意看到用户将手指抬离屏幕的位置而不是他们触及的位置.


Rob*_*ack 7

只想扔一个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
    }
}
Run Code Online (Sandbox Code Playgroud)

要么

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
}
Run Code Online (Sandbox Code Playgroud)

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


Kup*_*iOS 6

将UIGestureRecognizer与地图视图一起使用可能更好更简单,而不是尝试将其子类化并手动拦截触摸.

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

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

步骤2:接下来,实现shouldRecognizeSimultaneouslyWithGestureRecognizer并返回YES,这样您的点击手势识别器可以与地图同时工作(否则地图上的点击不会被地图自动处理):

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer 
shouldRecognizeSimultaneouslyWithGestureRecognizer
    :(UIGestureRecognizer *)otherGestureRecognizer
{
   return YES;
}
Run Code Online (Sandbox Code Playgroud)

第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);
}
Run Code Online (Sandbox Code Playgroud)