开发者

How to get the location of a touch in touchesBegan function

开发者 https://www.devze.com 2023-01-14 14:21 出处:网络
I tried the followin开发者_Go百科g code, but it doesn\'t work. How should it be modified? - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event

I tried the followin开发者_Go百科g 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;


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!

0

精彩评论

暂无评论...
验证码 换一张
取 消