是否可以将UIView上的用户所做的触摸坐标与plist或txt格式的一个商店进行比较?这个论点看起来像这样;
if (user touch coordinate == touch coordinate stored in plist or text)
then
(do something)
else
(do something)
如果可能,我应该以什么格式编写列表中的坐标以及如何在程序中将其关联起来?
提前感谢,如果你发现我的问题有点不自在,那就很抱歉。
答案 0 :(得分:5)
不确定是否存在单线解决方案。
在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"];
答案 1 :(得分:3)
您可能正在寻找的功能是NSStringFromCGPoint()
和CGPointFromString()
。
但是两个触摸坐标几乎肯定不会完全相同。你应该几乎永远不要将CGFloats
与==
进行比较,更不用说从手指触摸这样的模拟输入中得到的。您需要比较它们是否“足够接近”。有关如何测量两点之间距离的一个很好的示例,请参阅this blog。您希望该结果小于某个适合您目的的值(epsilon或“一小部分”)。