我该如何获取UIView中手指点击的坐标?(我不想使用大量按钮的数组)
谢谢。
谢谢。
有两种方法可以实现这个功能。如果你已经有了一个正在使用的 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
}
}
Swift 3的答案
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.tapAction(_:)))
yourView.addGestureRecognizer(tapGesture)
func tapAction(_ sender: UITapGestureRecognizer) {
let point = sender.location(in: yourView)
}
- (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
。如果您搜索此方法,则会找到几个教程。苹果公司的MoveMe示例是一个不错的选择。
func handleFrontTap(gestureRecognizer: UITapGestureRecognizer) {
print("tap working")
if gestureRecognizer.state == UIGestureRecognizerState.Recognized
{
`print(gestureRecognizer.locationInView(gestureRecognizer.view))`
}
}
Swift 5.6:
您可以在您的UIResponder中覆盖以下内容(UIView和UIViewController都继承自它):
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
if let touch = touches.first {
let point = touch.location(in: someView)
print("x = \(point.x), y = \(point.y)")
}
}
或者在您的手势识别处理程序中:
@objc func handleLongPress(gestureRecognizer: UILongPressGestureRecognizer) {
let point = gestureRecognizer.location(in: someView)
print("x = \(point.x), y = \(point.y)")
}