当UIButton被触发时,你如何获得touchesBegan坐标?

我有一个touchesBegan方法设置为在用户触摸屏幕时拾取坐标。 除非我触摸UIButton,否则它的效果很好。 如何使按钮触发touchesBegan方法呢?

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

[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]; 

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

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

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

尝试重写UIButton类,并在touchesBegan方法中调用[super touchesBegan ..]。