【问题标题】:CollectionViewCell press effectCollectionViewCell 按下效果
【发布时间】:2017-06-25 14:45:33
【问题描述】:

我想在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
}

【问题讨论】:

  • 您遇到的问题请提一下。
  • 你击中的地方。
  • 如果我不做任何操作,它会给出预期的结果。当我在计时器代码下方进行任何计算时,颜色变化仅在几个延迟后触发

标签: ios ipad swift3 uicollectionview uicollectionviewcell


【解决方案1】:

.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
            })
        }
    }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-04
    • 2023-03-31
    • 1970-01-01
    相关资源
    最近更新 更多