簡體   English   中英

UICollectionView刷新后重復並重新排序單元格內容

[英]UICollectionView Repeats and Reorders Cell Content When Refreshed

我正在嘗試完成iTunes U CS193P iOS編程課程。 作為Set游戲實現的一部分,我使用UICollectionView顯示卡時UICollectionView一些問題。 單擊卡導致UICollectionView刷新時,我看到一個非常奇怪的行為。 內容將重新排序,有時還會在視圖中重復。 請參見此處的前后兩個示例。

我相當確定這與我的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;
}

謝謝您的幫助。

當實現cellForRowAtIndexPath / cellForItemAtIndexPath方法時,必須完全配置從出隊方法返回的每個單元。

僅當該行的卡對象為SetCard類型時,您的代碼才配置單元格。 如果卡對象不是SetCard,則將單元格留空。 這意味着,如果以前從出隊方法中獲取的單元格曾經用於顯示SetCard,但card對象不是SetCard,則該單元格的視圖將不會更改,並且仍會顯示舊值。

如果卡對象不是SetCard類,則在if語句中添加else子句,以將字段設置為其默認狀態。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM