我正在为iPad制作一个图形计算器应用程序,我想添加一个功能,用户可以在图表视图中点击一个区域,弹出一个文本框,显示他们触摸的点的坐标。我如何从中获得CGPoint?
答案 0 :(得分:47)
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];
这里,当您想要使用主视图或主视图的子视图做某事时,此代码使用
答案 1 :(得分: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);
}
如果您更愿意看到用户将手指从屏幕上抬起而不是放在他们的位置,您可以使用“touchesEnded”。
答案 2 :(得分:6)
将UIGestureRecognizer与地图视图一起使用可能更好更简单,而不是尝试将其子类化并手动拦截触摸。
步骤1:首先,将手势识别器添加到地图视图中:
UITapGestureRecognizer *tgr = [[UITapGestureRecognizer alloc]
initWithTarget:self action:@selector(tapGestureHandler:)];
tgr.delegate = self; //also add <UIGestureRecognizerDelegate> to @interface
[mapView addGestureRecognizer:tgr];
步骤2:接下来,实现shouldRecognizeSimultaneouslyWithGestureRecognizer并返回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);
}
答案 3 :(得分:6)
只想投入一个 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
}
}
OR
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
都将包含视图中触及的点。
答案 4 :(得分:3)
如果您使用UIGestureRecognizer
或UITouch
对象,则可以使用locationInView:
方法检索用户触摸的给定视图中的CGPoint
。
答案 5 :(得分:0)
func handleFrontTap(gestureRecognizer: UITapGestureRecognizer) {
print("tap working")
if gestureRecognizer.state == UIGestureRecognizerState.Recognized {
`print(gestureRecognizer.locationInView(gestureRecognizer.view))`
}
}