node ninja
node ninja

Reputation: 33036

How to get the location of a touch in touchesBegan function

I tried the following code, but it doesn't work. How should it be modified?

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    location = [touches locationInView:self];
}

In the h files I have defined location like this:

CGPoint location;

Upvotes: 0

Views: 1841

Answers (1)

vfn
vfn

Reputation: 6066

The (NSSet *)touches will give you all the current touches on the screen. You will need to go on each touch on this set and get it's coordinate.

These touches are members of UITouch class. Have a look at the UITouch class reference.

for instance you would do:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    for (UITouch *touch in touches) {
        CGPoint location = [touch locationInView:self];

        // Do something with this location
        // If you want to check if it was on a specific area of the screen for example
        if (CGRectContainsPoint(myDefinedRect, location)) {
            // The touch is inside the rect, do something with it
            // ...
            // If one touch inside the rect is enough, break the loop
            break;
        }
    }
}

Cheers!

Upvotes: 1

Related Questions