tags:

views:

19

answers:

1

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;
+1  A: 

Hey @awakeFromNib,

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!

vfn
Is there a way to directly access the first touch so that a for loop doesn't need to be used?
awakeFromNib
You can set a break by end of the for loop, to make it run only once. Or you can get anyObject as suggested by @Vladimir.
vfn