我正在为iPad图形计算器应用程序,我想增加一个功能,用户可以在图表视图中点击某个区域做一个文本框弹出来显示他们触摸的点的坐标。 我怎样才能从这个CGPoint?
Answer 1:
您有两种方式...
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];
在这里,当你想要做财产以后你perticular对象或您的MAINVIEW的子视图此代码使用
Answer 2:
试试这个
- (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”如果你宁愿看到用户解除他们的手指离开屏幕,而不是在那里降落。
Answer 3:
它可能会更好和更简单的使用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);
}
Answer 4:
只是想在斯威夫特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
将包含在视图触摸的点。
Answer 5:
如果您使用的UIGestureRecognizer
或UITouch
对象,你可以使用locationInView:
方法来检索CGPoint
给定观点的用户感动之内。
Answer 6:
func handleFrontTap(gestureRecognizer: UITapGestureRecognizer) {
print("tap working")
if gestureRecognizer.state == UIGestureRecognizerState.Recognized {
`print(gestureRecognizer.locationInView(gestureRecognizer.view))`
}
}
文章来源: How to get a CGPoint from a tapped location?