objective-c - 比较触摸坐标

标签 objective-c plist coordinates touch

是否可以将用户在 UIView 上的触摸坐标与 plist 或 txt 格式的商店进行比较?论证看起来像这样;

  if (user touch coordinate == touch coordinate stored in plist or text)
  then
    (do something)
  else
    (do something)

如果可能,我应该以什么格式在列表中写入坐标以及如何在程序中关联它?

如果您发现我的问题有点新手,请提前致谢。

最佳答案

不确定是否有单行解决方案。

在 UITouch 实例上,locationInView: 方法返回一个 CGPoint 结构(x 和 y 坐标,均为 float 类型)。所以你可以将 x 和 y 坐标存储在你的 plist 中,然后将它们与你当前触摸的 x 和 y 坐标进行比较。

编辑: 此外,在比较坐标时,您可能希望使用两点之间的距离来确定何时“命中”。

编辑: 下面是加载和写入属性列表的示例代码,其中的值基于 NSDictionary:

- (NSMutableDictionary *)loadDictionaryFromPList: (NSString *)plistName
{
    NSString *plistPath = [[NSBundle mainBundle] pathForResource:plistName ofType:@"plist"];
    NSDictionary *immutableDictionary = [NSDictionary dictionaryWithContentsOfFile: plistPath];
    NSMutableDictionary *mutableDictionary = [NSMutableDictionary dictionaryWithDictionary: immutableDictionary];
    return mutableDictionary;
}


- (void)saveDictionary: (NSDictionary *)mySettings toPList: (NSString *)plistName
{
    NSString *plistPath = [[NSBundle mainBundle] pathForResource:plistName ofType:@"plist"];
    [mySettings writeToFile: plistPath atomically: YES];
}

计算UITouches两个位置之间距离的方法:

-(CGFloat) distanceBetween: (CGPoint) point1 and: (CGPoint)point2
{
    CGFloat dx = point2.x - point1.x;
    CGFloat dy = point2.y - point1.y;
    return sqrt(dx*dx + dy*dy );
}

最后,使用属性列表中的值来确定用户是否点击了先前位置的代码:

CGPoint currentTouchLocation = [currentTouch locationInView:self];

// Lookup last Touch location from plist, and handle case when current Touch matches it:
NSMutableDictionary *mySettings = [self loadDictionaryFromPList: @"MySettings"];
NSNumber *lastXCoordinate = [mySettings objectForKey:@"lastXCoordinate"];
NSNumber *lastYCoordinate = [mySettings objectForKey:@"lastYCoordinate"];
if (lastXCoordinate && lastYCoordinate)
{
    CGPoint lastTouchLocation = CGPointMake([lastXCoordinate floatValue], [lastYCoordinate floatValue]);
    CGFloat distanceBetweenTouches = [self distanceBetween: currentTouchLocation and: lastTouchLocation];
    if (distanceBetweenTouches < 25) // 25 is just an example
    {
        // Handle case where current touch is close enough to "hit" previous one
        NSLog(@"You got a hit!");
    }
}

// Save current touch location to property list:
[mySettings setValue: [NSNumber numberWithFloat: currentTouchLocation.x] forKey: @"lastXCoordinate"];
[mySettings setValue: [NSNumber numberWithFloat: currentTouchLocation.y] forKey: @"lastYCoordinate"];
[self saveDictionary:mySettings toPList: @"MySettings"];

关于objective-c - 比较触摸坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1570108/

相关文章:

ios - 无法在 Swift 中导入 Obj-C 框架

ios - 敏感信息应该存储在哪里?

c++ - 查找地球坐标(纬度、经度)、距离(米)和方位(角度)

objective-c - UITableView 刷新数据

iphone - objc_setAssociatedObject 在 iPhone 模拟器中不可用

shell - 修改 *plist 文件中的子键

xcode - Xcode 是否将 plist 隐式转换为二进制格式?

java - Canvas 坐标不准确地显示我的位图

Python,对坐标对进行操作的有效方法

iphone - 控制完成按钮