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

时间:2010-12-22 05:57:25

标签: iphone objective-c ios ipad

我设置了touchesBegan方法,用于在用户触摸屏幕时拾取坐标。它很有效,除非我触摸UIButton。如何使按钮触发touchesBegan方法?

2 个答案:

答案 0 :(得分:49)

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

[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 : %f y : %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获得了此代码并进行了一些小的更改。

答案 1 :(得分:0)

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