自定义选择视图的 UICollectionView 单元格出队问题

UICollectionView cell dequeue issue with custom selection view

我对 UICollectionView 及其出列机制有一个非常令人沮丧的问题。

简而言之,我有一个自定义的 UIView,里面有一个标签。我将其设置为自定义单元格中的选择背景视图,如下所示:

//My Custom Cell Class    
- (instancetype)initWithCoder:(NSCoder *)aDecoder{
        self = [super initWithCoder:aDecoder];

        if(self){
            _selectionView = (MyCustomView *)[[[NSBundle mainBundle] loadNibNamed:@"MyNibName" owner:self options:nil] objectAtIndex:0];
            self.selectedBackgroundView = _selectionView;
            [self bringSubviewToFront:_selectionView];
        }
        return self;
    }

请注意,单元格和 selectedBackgroundView 的所有布局工作等都是在笔尖中完成的。

Whenever the cell is selected, I'd like to set custom text in the label for selectionView so in my custom cell I also have the following method:

//In my Custom cell class
- (void) setSelectedViewLabelText:(NSString *)paramText{

    if(!self.isSelected){
        return;
    }
    self.selectionView.label.text = paramText;   
}

要设置我的 UICollectionViewController 中的文本:

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{

    MyCellClass *selectedCell = (MyCellClass *)[self.collectionView cellForItemAtIndexPath:indexPath];
    [selectedCell setSelectedViewLabelText:someString];  
}

问题是每当 UICollectionView 回收单元格时,它都会再次初始化它们,显然没有调用 setSelectedViewLabelText 方法。

我有一种恼人的感觉,我可能必须跟踪选定的 indexPaths 并枚举它们以查看是否选择了一个单元格并调用该方法,但我有潜在的大数据集并且可以预见这将如何成为性能问题....有什么想法吗?

提前致谢!

跟踪您选择的单元格,例如:

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{    
    MyCellClass *selectedCell = (MyCellClass *)[self.collectionView cellForItemAtIndexPath:indexPath];
    [selectedCell setSelectedViewLabelText:someString];
    selectedIndexPath = indexPath;
}

cellForItemAtIndexPath 检查 indexPath:

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    //.......

    if([selectedIndexPath isEqual:indexPath]){
        [cell setSelectedViewLabelText:someString];
    }
    return cell;
}

希望这对您有所帮助..:)