使用 Swift 3 按下时动画单元格 [英] Animate cell when pressed using Swift 3

查看:20
本文介绍了使用 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆