SHERRIE CRANE
SHERRIE CRANE

Reputation: 133

How to get the location of a touch using touchesEnded inside a button

I am using the code below to try and get the location of a touch but it only works outside of the button. Eg. it prints the console line if the touch is outside the button but if not, it doesn't work. What is solution to this? Here is the code:

    - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {

        UITouch *touch = [touches anyObject];
        CGPoint touchPoint = [touch locationInView:self.appleClickedButton];
        NSLog(@"%f",touchPoint);
        NSLog(@"%f",touchPoint); 
    }

Thanks

Upvotes: 1

Views: 1270

Answers (3)

eik
eik

Reputation: 4618

You could try UIButtons addTarget:action:forControlEvents: with a control event mask including UIControlEventTouchUpInside.

Upvotes: 0

Naz Mir
Naz Mir

Reputation: 1028

Here's how you can get touch location when a UIButton is tapped. (just make sure you link TouchUpInside event with the IBAction)

- (IBAction)buttonTapped:(id)sender forEvent:(UIEvent*)event
{
    UIView *button = (UIView *)sender;
    UITouch *touch = [[event touchesForView:button] someObject];
    CGPoint touchPointInButton = [touch locationInView:button];
    NSLog(@"Location in button: %f, %f", touchPointInButton.x, touchPointInButton.y);
}

Once you get the touch point inside the button, you can calculate what the touch point would be in the super view.

Upvotes: 1

Danyun Liu
Danyun Liu

Reputation: 3090

When you touch inside the button. the event has been handled by the button. The view which contains the button will not get the touch event.

You can create a custom class inherit from the UIButton and override the method, but please make sure to call the the method in the super class or some actions such as TouchUpInside will not work correctly.

Upvotes: 0

Related Questions