首页 文章

CollectionViewCell按效果

提问于
浏览
0

我想在 didSelectItem 上为 collectionViewCell 提供新闻效果 . 点击后我想添加一些颜色,经过一段时间后我想恢复颜色 . 在尝试下面的代码时,仅在延迟一段时间后才会添加按下效果 . 谁能建议如何实现这一目标?

DispatchQueue.global(qos: .utility).async {
    let cell = collectionView.cellForItem(at: indexPath) as ..cell

    // Change bg color for foreground layer
    DispatchQueue.main.async {
        Timer.scheduledTimer(timeInterval: 0.10, target: self, selector: #selector(self.updateCell(timer:)) , userInfo: ["cell":cell,"collectionview":collectionView], repeats: false)
    }
    // Some calculations
}

1 回答

  • 0

    通常应该在主线程中调用 .cellForItem(at: indexPath) as ..cell ,如果你从实用程序队列中执行它,你可能会看到奇怪的行为

    我建议不要自己使用DispatchQueues并处理动画计时,已经有一个很好的功能可以完全满足您的需求 . 这是我的建议:

    override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let cell = collectionView.cellForItem(at: indexPath) as ..cell
        UIView.animate(withDuration: 0.2, delay: 0.4, options: .curveEaseInOut, animations: {
            cell.backgroundColor = UIColor.red
        }, completion: { _ in
            // here the animation is done
        })
    }
    

    使用更好的解决方案进行更新

    无论如何,我认为比在 UICollectionViewDelegatedidSelectItemAt 函数中处理动画更好的方法将覆盖单元格的 isSelected 属性 .

    在这个例子中,每当UICollectionViewCell的选择状态改变时,我都会为backgroundColor设置动画 - 选中时为红色,否则为绿色 . 只需用你想要的任何风格来代替它 .

    class YourCell: UICollectionViewCell {
    
    
        override var isSelected: Bool {
            willSet(newValue) {    
                let newColor = isSelected ? UIColor.red : UIColor.green
                UIView.animate(withDuration: 1, delay: 0.4, options: .curveEaseInOut, animations: {
                    self.backgroundColor = newColor
                }, completion: { _ in
                    // here the animation is done - nothing to do here probably
                })
            }
        }
    
    }
    

相关问题