【发布时间】:2012-05-20 07:57:00
【问题描述】:
我正在为 iPad 开发一个图形计算器应用程序,我想添加一个功能,用户可以点击图形视图中的一个区域来弹出一个文本框,显示他们触摸的点的坐标。我怎样才能从中获得 CGPoint?
【问题讨论】:
标签: ios xcode ipad touch cgpoint
我正在为 iPad 开发一个图形计算器应用程序,我想添加一个功能,用户可以点击图形视图中的一个区域来弹出一个文本框,显示他们触摸的点的坐标。我怎样才能从中获得 CGPoint?
【问题讨论】:
标签: ios xcode ipad touch cgpoint
试试这个
- (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 或UITouch 对象,您可以使用locationInView: 方法在用户触摸的给定视图中检索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];
这里,当你想对你的特定对象或主视图的子视图做某事时使用此代码
【讨论】:
将 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);
}
【讨论】:
func handleFrontTap(gestureRecognizer: UITapGestureRecognizer) {
print("tap working")
if gestureRecognizer.state == UIGestureRecognizerState.Recognized {
`print(gestureRecognizer.locationInView(gestureRecognizer.view))`
}
}
【讨论】:
只想抛出一个 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 都将包含视图中被触摸的点。
【讨论】: