ios - 在 didHighlightItemAt 和 didUnhighlightItemAt 上更改 UICollectionViewCell 的背景在滚动时闪烁

标签 ios swift uicollectionview

我想在用户点击或关注它时更改 UICollectionView 中单元格的背景。我想在用户点击后立即提供不断变化的背景反馈,所以我在 UICollectionViewDelegateFlowLayout 中实现了这两个方法:

func collectionView(_ collectionView: UICollectionView, didHighlightItemAt indexPath: IndexPath) {
    if let cell = collectionView.cellForItem(at: indexPath) as? CustomCell {
        cell.highlight()
    }
}

func collectionView(_ collectionView: UICollectionView, didUnhighlightItemAt indexPath: IndexPath) {
    if let cell = collectionView.cellForItem(at: indexPath) as? CustomCell {
        cell.unhighlight()
    }
}

它有效,但不幸的是,当用户在集合上滚动时,调用了 didHighlightItemAt 方法并立即调用了 didUnhighlightItemAt 方法,因此这导致单元格闪烁。

我想知道如何安排调用 cell.highlight 0.1 秒,如果 didUnhighlightItemAt 调用早于 0.1 秒,我会取消高亮调用。

但是有没有更好的解决方案呢?

类似的效果发生在“设置”应用中(但更难做到,在我的应用中更容易看到闪烁的单元格):

Demo

最佳答案

- (void)collectionView:(UICollectionView *)collectionView didHighlightItemAtIndexPath:(NSIndexPath *)indexPath {
    UICollectionViewCell *cell = [collectionView cellForItemAtIndexPath:indexPath];
    cell.backgroundColor = UIColor.redColor;
}

- (void)collectionView:(UICollectionView *)collectionView didUnhighlightItemAtIndexPath:(NSIndexPath *)indexPath {
    UICollectionViewCell *cell = [collectionView cellForItemAtIndexPath:indexPath];
    cell.backgroundColor = UIColor.orangeColor;
}

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

    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    cell.backgroundColor = UIColor.orangeColor;
    return cell;
}

输出:

enter image description here

关于ios - 在 didHighlightItemAt 和 didUnhighlightItemAt 上更改 UICollectionViewCell 的背景在滚动时闪烁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47882130/

相关文章:

ios - 获取选中标记的行并发送到控制台

objective-c - 奇怪的崩溃问题为 :- Dispatch queue: com. apple.root.default-overcommit-priority

ios - CLLocationManager 委托(delegate)方法没有被调用(集成了谷歌地图)

ios - 启用分页时将水平滚动 Collection View 的单元格居中,并使其他单元格部分可见

ios - 为collectionView添加deleteItemAtIndexPath

ios - Firebase In-App Messaging 真的适用于 iOS 吗?

ios - 如何使用 Swift 动态访问数组中的项目

ios - 将 PDFDocument 作为 NSData 保存到 CoreData(如何将其转换为 NSData?)

ios - 从 Parse (ios) 中的指针行获取数据

ios - 在 reloadData 上禁用 UICollectionView 动画