Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 751
kernelpanic Avatar asked Dec 22 '10 05:12

kernelpanic


1 Answers

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 ev as below,

- (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-iphone and made some minor changes.

like image 153
EmptyStack Avatar answered Oct 26 '22 11:10

EmptyStack