重载数据后,UICollectionView单元格保持突出显示

ric*_*chy 12 objective-c reloaddata ios uicollectionview

UICollectionView在单元格内部有标签,可以定期自动更改.当此更新触发时,我调用reloadDataUICollectionView并设置单元格以更改背景颜色[UICollectionViewCell setHighlighted:].

问题是如果用户按住某个单元格然后进行更新,则当用户释放该单元格时会保持突出显示并且也不能再进行选择.

我注意到dequeueReusableCellWithReuseIdentifier:forIndexPath:reloadData之后在单元格上调用setHighlighted.

我也试过reloadSections:而不是reloadData,这解决了细胞被"卡住"的问题,但是当它被调用时会导致细胞淡出并进入细胞.

将呼叫置于内部performBatchUpdates:似乎也无法解决问题.

jam*_*one 6

在单元格的类中尝试调用:

- (void)prepareForReuse {
    [super prepareForReuse];
    [self setHighlighted:NO];
    ... Any other custom stuff that should be cleaned up ...
}
Run Code Online (Sandbox Code Playgroud)

问题是,您可能正在进行不同的背景着色,然后突出显示单元格通常会自行进行.通常,单元格的超类会撤消这些更改prepareForReuse,但它不知道您的更改.


sil*_*vsk 2

我使用以下方法作为解决方法:

// Both highlightedData and lastHighlightedData are only needed if you want to prevent user from selecting a cell which data changed during the reload. If not needed, a boolean may be used instead
@property (nonatomic) id highlightedData;
@property (nonatomic) id lastHighlightedData;
@property (nonatomic) BOOL pendingCollectionViewReload;

// Wrap the reloadData call. Enqueue it if there's a highlighted cell:
- (void)reloadCollectionView
{
    if (self.highlightedData) {
        self.pendingCollectionViewReload = YES;
        return;
    }

    [self.collectionView reloadData];
    self.pendingCollectionViewReload = NO;
}

// When a cell is highlighted, save its index, or better the related data:
- (void)collectionView:(UICollectionView *)collectionView didHighlightItemAtIndexPath:(NSIndexPath *)indexPath
{
    // Save data at indexPath to self.highlightedData
}    

// Then reload the data when the cell is unhighlighted:
- (void)collectionView:(UICollectionView *)collectionView didUnhighlightItemAtIndexPath:(NSIndexPath *)indexPath
{
    self.lastHighlightedData = self.highlightedData;
    self.highlightedData = nil;

    if (self.pendingCollectionViewReload) {
        [self reloadCollectionView];
    }
}

// The following can be used from shouldPerformSegueWithIdentifier or didSelectItemAtIndexPath to prevent actions if the data associated with the indexPath changed:
- (BOOL)selectedDataEquals:(id)data
{
    // I used lastHighlightedData in addition to highlightedData because this function may be used after the didUnhighlightItemAtIndexPath was called:
    return (self.highlightedData && self.highlightedData == data) || (!self.highlightedData && self.lastHighlightedData == data);
}
Run Code Online (Sandbox Code Playgroud)