Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

iphone - How do I get the coordinates for finger tapping in UIView?

How do I get the coordinates for finger tapping in UIView? (I would prefer not to use a big array of buttons)

Thank you

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

There’re two ways to accomplish this. If you’ve already got a subclass of UIView that you’re using, you can just override the -touchesEnded:withEvent: method on that subclass, like this:

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *aTouch = [touches anyObject];
    CGPoint point = [aTouch locationInView:self];
    // point.x and point.y have the coordinates of the touch
}

If you’re not already subclassing UIView, though, and the view is owned by a view controller or whatever, then you can use a UITapGestureRecognizer, like this:

// when the view's initially set up (in viewDidLoad, for example)
UITapGestureRecognizer *rec = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapRecognized:)];
[someView addGestureRecognizer:rec];
[rec release];

// elsewhere
- (void)tapRecognized:(UITapGestureRecognizer *)recognizer
{
    if(recognizer.state == UIGestureRecognizerStateRecognized)
    {
        CGPoint point = [recognizer locationInView:recognizer.view];
        // again, point.x and point.y have the coordinates
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...