collectionView 单元格重叠

collectionView cells overlapping

我正在尝试创建具有 4 种不同类型的多个 collectionViewCells。每个细胞对这 4 种类型中的一种都有不同的看法。这些类型的每个视图都可以根据用户选择具有不同的内容。

我遇到的问题是,当屏幕上出现多个 views/cells 相同类型的卡片时,某些卡片 overlapping/not 正确加载。

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    Card *card = [[[usermanager getSelectedUser] getCards] objectAtIndex:indexPath.item];
    NSLog(@"CARD LOADING: %@", card.title);
    [card setupLayout];
    UICollectionViewCell *cell;
    if(card.type.intValue == 1){
        cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"lifestyleCell" forIndexPath:indexPath];
    }else if(card.type.intValue == 2){
        cell= [collectionView dequeueReusableCellWithReuseIdentifier:@"sceneCell" forIndexPath:indexPath];
    }else if(card.type.intValue == 3){
        cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"energyCell" forIndexPath:indexPath];
    }else if(card.type.intValue == 4){
        cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"productCell" forIndexPath:indexPath];
    }else{
        cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cardCell" forIndexPath:indexPath];
    }
    [cell addSubview:card];

    //Add dropshadow
    cell.contentView.layer.borderWidth = 1.0f;
    cell.contentView.layer.borderColor = [UIColor clearColor].CGColor;
    cell.contentView.layer.masksToBounds = YES;

    cell.layer.shadowColor = [UIColor blackColor].CGColor;
    cell.layer.shadowOffset = CGSizeMake(0, 5.0f);
    cell.layer.shadowRadius = 2.0f;
    cell.layer.shadowOpacity = 0.5f;
    cell.layer.masksToBounds = NO;

    return cell;
}

卡片是我添加到单元格的视图。如上所述,这些卡片有多种类型。

当您滚动 UICollectionView 时,屏幕外消失的单元格将重新用于出现在屏幕上的新单元格。这意味着,如果您在 collectionView:cellForItemAtIndexPath: 方法中添加子视图,则在重新使用该单元格时,它们仍将是该单元格视图层次结构的一部分。每次cell被重新使用,调用[cell addSubview:card]时都会添加一个新的subview。您的卡片子视图将简单地堆叠在一起。

您似乎在使用 Card 对象的集合、自定义 UIView 子类来存储每个用户的牌组。相反,我建议您将模型与视图分开 - 将每张卡片存储为一个简单的数据模型,该模型独立于它的显示方式来表示卡片(请参阅 MVC)。然后你可以创建一个可以显示任何卡片的自定义 UICollectionViewCell 子类。在您的 collectionView:cellForItemAtIndexPath: 中,您只需根据相应的卡片数据重新配置单元格的视图。这样你就不需要在你的 collectionView:cellForItemAtIndexPath: 方法中调用 addSubview:

尝试使用:

cell.clipsToBounds = YES;