【发布时间】:2014-05-16 22:40:34
【问题描述】:
我正在尝试完成 iTunes U CS193P iOS 编程课程。我在使用 UICollectionView 来显示卡片作为 Set 游戏实现的一部分时遇到了一些问题。单击导致UICollectionView 刷新的卡片时,我看到了一个非常奇怪的行为。内容将被重新排序,有时会在视图中重复。请参阅here 之前和之后的两个示例。
我相当肯定这与我的UICollectionView 实现有关,因为游戏逻辑已经使用按钮进行了测试。
点击“视图控制器”中的代码:
- (IBAction)touchCard:(UITapGestureRecognizer *)sender {
CGPoint tapLocation = [sender locationInView:self.cardCollectionView];
NSIndexPath *indexPath = [self.cardCollectionView indexPathForItemAtPoint:tapLocation];
if (indexPath) {
[self.game chooseCardatIndex:indexPath.item];
[self updateUI];
}
}
updateUI 代码:
- (void)updateUI
{
// Reload data for cardCollectionView
[self.cardCollectionView reloadData];
// For each cell within the UICollectionViewCell
for (UICollectionViewCell *cell in [self.cardCollectionView visibleCells]) {
NSIndexPath *indexPath = [self.cardCollectionView indexPathForCell:cell];
Card *card = [self.game cardAtIndex:indexPath.item];
if([card isKindOfClass:[SetCard class]]) {
SetCard *setcard = (SetCard *)card;
NSLog([NSString stringWithFormat:@"index %d updated with %d,%d,%d,%d",indexPath.item,setcard.rank,setcard.color,setcard.shape,setcard.pattern]);
// Updates individual cards for each cardCollectionView
[self updateCell:cell usingCard:card animated:YES];
}
}
}
这会更新单元格视图:
- (void)updateCell:(UICollectionViewCell *)cell usingCard:(Card *)card animated:(BOOL)animated
{
setCardView *cardView = ((setCardCellView *)cell).setCardV;
if([card isKindOfClass:[SetCard class]]) {
SetCard *setCard = (SetCard *)card;
// Set attributes of the card in the cardView
cardView.rank = setCard.rank;
cardView.shape = setCard.shape;
cardView.pattern = setCard.pattern;
cardView.color = setCard.color;
// Set chosen cards
cardView.selected = setCard.isChosen;
}
}
终于collectionView所需的方法cellForItemAtIndexPath:
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:[self reuseIdentifier] forIndexPath:indexPath];
Card *card = [self.game cardAtIndex:indexPath.item];
[self updateCell:cell usingCard:card animated:YES];
return cell;
}
感谢您的帮助。
【问题讨论】:
标签: ios objective-c cocoa-touch uikit uicollectionview