0

我正在尝试将 UITouches 存储在字典或数组中并且遇到了一些麻烦。存储 CGPoints 工作正常,但存储 UITouches 不行。

进一步说明:在触摸开始时初始化数组,将每个UITouch存储在一个数组中,当触摸结束时我想输出数组。我一直在寻找一段时间,但我还没有找到任何示例代码来执行此操作。

NSMutableArray *touchesArray;
NSMutableArray *pointArray;

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{

    touchesArray = [[NSMutableArray alloc] init];

    pointArray = [[NSMutableArray alloc] init];
}

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{

    UITouch *touch = [touches anyObject];
    CGPoint currentPoint = [touch locationInView:self];
     [pointArray addObject:[NSValue valueWithCGPoint: currentPoint]];

    [touchesArray addObject:[NSValue valueWithPointer:(__bridge const void *)(touch)]];

    for (UITouch *touch in touches)
    {
        NSLog(@"x location %f",[touch locationInView:self].x);
    }


}

-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{        

    for (UITouch *touch in touches)
    {        
        NSLog(@"%f",[touch locationInView:self].x);
    }

    for(id p in pointArray){
        NSValue *val = p;
        CGPoint point = [val CGPointValue];
        NSLog(@"%f",point.x);
    }

    //ERROR!
    for(id p in touchesArray){
        NSValue *val = p;
        UITouch *t = (UITouch*) p;
        NSLog(@"%@",[t timestamp]);
    }

}
4

2 回答 2

1

使用包装器对象对我有用。UITouch 总是指向同一个地址。

#import "TouchInfo.h"

@implementation TouchInfo

@synthesize timestamp;
@synthesize location;

@end


-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
int ns = [touches count];
NSLog(@"number of touches  %i",ns);
for(UITouch *touch in touches)
{
    NSNumber *val = [NSNumber numberWithFloat:[touch timestamp]];        
    TouchInfo *touchInfo = [[TouchInfo alloc] init];
    touchInfo.location = [touch locationInView:self];
    touchInfo.timestamp = [touch timestamp];
}
}

-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{

int nt = [touchesArray count];
for (int i = 0; i < nt; i++){
    TouchInfo *touchInfo = (TouchInfo*)[touchesArray objectAtIndex:i];
    NSLog(@"%f  %f   %f",touchInfo.timestamp,touchInfo.location.x,touchInfo.location.y);    

}
}
于 2012-10-01T10:41:48.147 回答
0

做这个:

 -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{

    if(!touchesArray){
    touchesArray = [[NSMutableArray alloc] init];
    }
    if(!pointArray){
    pointArray = [[NSMutableArray alloc] init];
    }
 }

现在

 -(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{

   UITouch *touch = [touches anyObject];

   [touchesArray addObject:touch];

   ..........
 }

检索时这样做:

 UITouch *touch = (UITouch*)[touchesArray objectAtIndex:0];
于 2012-09-27T10:13:18.063 回答