ios 触发 UIButton 时如何获取 touchesBegan 坐标?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4506584/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 18:22:08  来源:igfitidea点击:

How do you get the touchesBegan coordinates when a UIButton is triggered?

iphoneobjective-ciosipad

提问by Kevin Peters

I have a touchesBegan method set up to pick up the coordinates when the user touches the screen. It works great except when I touch down on a UIButton. How do I make it so that the button triggers the touchesBegan method too?

我设置了一个 touchesBegan 方法来在用户触摸屏幕时获取坐标。除了当我按下 UIButton 时,它工作得很好。如何使按钮也触发 touchesBegan 方法?

回答by EmptyStack

Add event handlers to the button, something like the following,

向按钮添加事件处理程序,如下所示,

[myButton addTarget:self action:@selector(dragBegan:withEvent:) forControlEvents: UIControlEventTouchDown];
[myButton addTarget:self action:@selector(dragMoving:withEvent:) forControlEvents: UIControlEventTouchDragInside];
[myButton addTarget:self action:@selector(dragEnded:withEvent:) forControlEvents: UIControlEventTouchUpInside | UIControlEventTouchUpOutside];

Handle the events as the following, you can get the touch point from the event evas below,

处理事件如下,您可以从事件ev 中获取接触点,如下所示,

- (void)dragBegan:(UIControl *)c withEvent:ev {
    NSLog(@"dragBegan......");
    UITouch *touch = [[ev allTouches] anyObject];
    CGPoint touchPoint = [touch locationInView:self.view];
    NSLog(@"Touch x : %f y : %f", touchPoint.x, touchPoint.y);
}

- (void)dragMoving:(UIControl *)c withEvent:ev {
    NSLog(@"dragMoving......");
}

- (void)dragEnded:(UIControl *)c withEvent:ev {
    NSLog(@"dragEnded......");
}

This is not my own answer. I got this code from http://sree.cc/iphone/handling-touche-events-for-uibuttons-in-iphoneand made some minor changes.

这不是我自己的答案。我从http://sree.cc/iphone/handling-touche-events-for-uibuttons-in-iphone得到了这个代码并做了一些小改动。

回答by Chandan Shetty SP

Try overriding UIButton class and in the touchesBegan method call [super touchesBegan..].

尝试覆盖 UIButton 类并在 touchesBegan 方法中调用 [super touchesBegan..]。