使用 Swift 3 按下时为单元格设置动画 [英] Animate cell when pressed using Swift 3
问题描述
我的问题很简单.我想为 collectionView 中的单元格设置动画.事实上,我想在单元格后面显示一个灰色背景并缩小里面的图像.
My problem is really simple. I would like to animate a cell within a collectionView. Indeed, I would like to show a grey background behind the cell and scale down the image inside.
与 Pinterest 的效果(几乎)相同:
It would be (almost) the same effect than Pinterest:
我曾经在按钮上编写动画,但我从来没有在单元格上这样做过.例如,如何将单元格链接到 touchUpInside 或 TouchDown 操作?
I used to code that animation on buttons, but I never did that on a cell. How can link a cell to a touchUpInside or TouchDown action for example ?
推荐答案
如果你想在触摸单元格时启动动画,你可以实现didHighlightItemAt
.您可能想在 didUnhighlightItemAt
中反转它:
If you want to start animation when you touch on the cell, you can implement didHighlightItemAt
. You probably want to reverse it in didUnhighlightItemAt
:
override func collectionView(_ collectionView: UICollectionView, didHighlightItemAt indexPath: IndexPath) {
UIView.animate(withDuration: 0.5) {
if let cell = collectionView.cellForItem(at: indexPath) as? CustomCell {
cell.imageView.transform = .init(scaleX: 0.95, y: 0.95)
cell.contentView.backgroundColor = UIColor(red: 0.95, green: 0.95, blue: 0.95, alpha: 1)
}
}
}
override func collectionView(_ collectionView: UICollectionView, didUnhighlightItemAt indexPath: IndexPath) {
UIView.animate(withDuration: 0.5) {
if let cell = collectionView.cellForItem(at: indexPath) as? CustomCell {
cell.imageView.transform = .identity
cell.contentView.backgroundColor = .clear
}
}
}
产生:
这篇关于使用 Swift 3 按下时为单元格设置动画的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!