如何在UIView中获取手指敲击的坐标?(我不喜欢使用一大堆按钮)
谢谢
发布于 2011-05-25 00:51:48
有两种方法可以做到这一点。如果您已经有了正在使用的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
}
}发布于 2017-08-16 21:04:24
Swift 3答案
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.tapAction(_:)))
yourView.addGestureRecognizer(tapGesture)
func tapAction(_ sender: UITapGestureRecognizer) {
let point = sender.location(in: yourView)
}发布于 2011-05-25 00:47:10
我想你的意思是识别手势(和触摸)。要开始寻找这样一个广泛的问题,最好的地方是苹果的示例代码Touches。它浏览了大量的信息。
https://stackoverflow.com/questions/6113860
复制相似问题