如何在touchesBegan函数中获取触摸的位置

时间:2010-08-30 00:30:27

标签: cocoa-touch

我尝试了以下代码,但它不起作用。应该如何修改?

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

在h文件中我定义了这样的位置:

CGPoint location;

1 个答案:

答案 0 :(得分:1)

(NSSet *)touches将为您提供屏幕上的所有当前触摸功能。你将需要在这一组上进行每次触摸并获得它的坐标。

这些接触是UITouch类的成员。看看UITouch class reference

例如,你会这样做:

- (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;
        }
    }
}

干杯!