Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
489 views
in Technique[技术] by (71.8m points)

ios - How do I get the tap coordinates on a custom UIButton?

I'm using XCode 4.4 developing for iOS 5 on an iPad and am using the Storyboard layout when creating my custom button.

I have the touch event correctly working and logging but now I want to get the x/y coordinates of the tap on my custom button.

If possible, I'd like the coordinates to be relative to the custom button instead of relative to the entire iPad screen.

Here's my code in the .h file:

- (IBAction)getButtonClick:(id)sender;

and my code in the .m file:

    - (IBAction)getButtonClick:(id)sender {

        NSLog(@"Image Clicked.");
    }

Like I said, that correctly logs when I tap the image.

How can I get the coordinates of the tap?

I've tried a few different examples from the internet but they always freeze when it displays a bunch of numbers (maybe the coordinates) in the log box. I'm VERY new to iOS developing so please make it as simple as possible. Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

To get touch location you can use another variant of button action method: myAction:forEvent: (if you create it from IB interface note "sender and event" option in arguments field: enter image description here)

Then in your action handler you can get touch location from event parameter, for example:

- (IBAction)myAction:(UIButton *)sender forEvent:(UIEvent *)event {
    NSSet *touches = [event touchesForView:sender];
    UITouch *touch = [touches anyObject];
    CGPoint touchPoint = [touch locationInView:sender];
    NSLog(@"%@", NSStringFromCGPoint(touchPoint));
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...