1

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

3 Answers 3

1

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.

0

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.

1
  • I'm not sure this is true. Don't you need to do some work, delegation, to get a button to not register a touch also? Otherwise a button will do both actions if there is a tap recognizer present.
    – timquinn
    Sep 8, 2013 at 22:46
0

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.