objective-c - 将 UITouch 存储在 NSArray 中

标签 objective-c ios

我正在尝试将 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]);
    }

}

最佳答案

使用包装对象对我有用。 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);    

}
}

关于objective-c - 将 UITouch 存储在 NSArray 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12618707/

相关文章:

ios - 在 -Swift.h 文件中找不到 'UNUserNotificationCenterDelegate' 的协议(protocol)声明

ios - 访问在 2 个 View Controller 之间传递的属性时的 EXC_BAD_ACCESS

ios - cellForRowAtIndexPath 中对象的潜在泄漏

objective-c - 如何在 ios 中为 Tableview 创建动态 TableCell

ios - 当行向左滑动时切换操作

ios - 将手势识别器添加到 UIImage,而不是 UIImageView

iOS - 相对于动态嵌入式框架,静态库框架的大小非常大

ios - 更改自定义表格 View 单元格的图像

ios - 如何使用字节数据创建 uint8_t?

ios - 无法使用 Xcode 8.2.1 提交包含 Here Maps Premium SDK 的存档