如何在UIView中获取手指敲击的坐标? (我不想使用大量的按钮)
谢谢
答案 0 :(得分:30)
有两种方法可以实现这一目标。如果你已经有了你正在使用的UIView的子类,你可以覆盖该子类上的-touchesEnded:withEvent:
方法,如下所示:
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *aTouch = [touches anyObject];
CGPoint point = [aTouch locationInView:self];
// point.x and point.y have the coordinates of the touch
}
如果您还没有将UIView子类化,并且该视图归视图控制器所有,那么您可以使用UITapGestureRecognizer,如下所示:
// when the view's initially set up (in viewDidLoad, for example)
UITapGestureRecognizer *rec = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapRecognized:)];
[someView addGestureRecognizer:rec];
[rec release];
// elsewhere
- (void)tapRecognized:(UITapGestureRecognizer *)recognizer
{
if(recognizer.state == UIGestureRecognizerStateRecognized)
{
CGPoint point = [recognizer locationInView:recognizer.view];
// again, point.x and point.y have the coordinates
}
}
答案 1 :(得分:2)
我认为你的意思是识别手势(和触摸)。开始寻找如此广泛问题的最佳位置是Apple的示例代码Touches。它会传递大量信息。
答案 2 :(得分:2)
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
CGPoint touchPoint = [touch locationInView:myView];
NSLog("%lf %lf", touchPoint.x, touchPoint.y);
}
你需要做这样的事情。 touchesBegan:withEvent:
是一种UIResponder
方法,UIView
和UIViewController
都来自{{1}}。如果你谷歌这个方法,那么你会发现几个教程。来自Apple的MoveMe样本很好。
答案 3 :(得分:2)
func handleFrontTap(gestureRecognizer: UITapGestureRecognizer) {
print("tap working")
if gestureRecognizer.state == UIGestureRecognizerState.Recognized
{
`print(gestureRecognizer.locationInView(gestureRecognizer.view))`
}
}
答案 4 :(得分:2)
斯威夫特3回答
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.tapAction(_:)))
yourView.addGestureRecognizer(tapGesture)
func tapAction(_ sender: UITapGestureRecognizer) {
let point = sender.location(in: yourView)
}