我正在创建一个拼图应用程序。当每一块被触摸时,想法是如果它被放置在正确的位置,则bool(droppedInPlace
)被分配YES
,并且如果被放置在错误的位置则被配置为NO
。然后我想我需要创建一个40个布尔(拼图块的数量)的数组,每个条目最初都会被设置为NO。创建并循环遍历数组bools
然后使用replaceObjectAtIndex
将此bool(droppedInPlace
)插入到一个数组中。然后我想循环这个数组。如果所有条目均为true/yes/1,则拼图完成,我将运行一些代码。
我在做这个时遇到了一些麻烦。我无法弄清楚如何编码我的想法。下面是我的代码:
-(void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
UIView *touchedView = [touch view];
// filename to be read from
NSString *filePath = [[NSBundle mainBundle]
pathForResource:
@"jigsawHomeCenterPoints"
ofType:@"plist"];
// array of cgpoints in string format
NSArray *jigsawHomeCentersArray = [NSArray arrayWithContentsOfFile:filePath];
// the tag number of the selected image
int tag = touchedView.tag;
NSLog(@"tag: %i", tag);
// says that the piece has not been dropped in it's holder
bool droppedInPlace = NO;
// if what has been touched is part of the array of images
if ([imagesJigsawPieces indexOfObject:touchedView] != NSNotFound) {
// preparing new snap-to-center position
// using (tag-1) as an index in the HomeCentersArray corresponds to where the image should be placed
// this was a conscious decision to make the process easier
CGPoint newcenter = CGPointFromString([jigsawHomeCentersArray objectAtIndex:tag-1]);
// the location of the current touch
CGPoint location = [touch locationInView:self.view];
// call the animate method upon release
[self animateReleaseTouch:touchedView withLocation:location];
// setting a proximity range - if it is within this 80x80 area the image will snap to it's corresponding holder (HomeCenter)
if (location.x > newcenter.x-40 && location.x < newcenter.x+40
&& location.y > newcenter.y-40 && location.y < newcenter.y+40) {
touchedView.center = newcenter;
touchedView.alpha = 1.0;
droppedInPlace = YES;
} else {
touchedView.alpha = 0.5;
droppedInPlace = NO;
}
NSLog(@"True or false: %i", droppedInPlace);
[self checkJigsawCompleted:droppedInPlace withTag:tag];
}
}
和校验功能:
-(void) checkJigsawCompleted:(BOOL)inPlace withTag:(NSInteger)tag {
NSMutableArray *piecesInPlace;
[piecesInPlace replaceObjectAtIndex:tag-1 withObject:[NSNumber numberWithBool:inPlace]];
//code to loop through array - check if all entries are true/yes/1
//if so, jigsaw is completed - run some other code
//else, do nothing
}
我实际上给出了我的故事板中1-40的所有图像标签。使用'replaceObjectAtIndex:(tag-1)'有意义吗?那些括号会确保我不会尝试访问-1索引吗? – garethdn 2012-04-04 11:14:22
想一想。如果第一个标记为0,括号如何防止标记-1为-1?当然,如果你手动设置IB的标签,只需要在1开始最低标签,你就会好起来的。 – jmstone617 2012-04-04 11:16:16
对不起,我认为我们的电线穿过那里 - 尽管你的意思是别的。我的最低标签的确是1. – garethdn 2012-04-04 11:29:05