我正在創建一個拼圖應用程序。當每一塊被觸摸時,想法是如果它被放置在正確的位置,則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