使一个CollectionViewCell在Swift中突出显示

Jel*_*l92 1 collections view cell jquery-animate swift

在过去的几个小时里,我试图完成以下任务:

在UICollectionview中,当我突出显示(向下触摸)一个单元格时,我希望它向内反射几个像素(更小的尺寸)并在释放时弹回到原始大小.

这是我到目前为止所尝试的:

override func collectionView(collectionView: UICollectionView,
didHighlightItemAtIndexPath indexPath: NSIndexPath) {


    collectionView.collectionViewLayout.invalidateLayout()
    let cell = collectionView.cellForItemAtIndexPath(indexPath)
    UIView.transitionWithView(cell!, duration: 1, options: UIViewAnimationOptions.CurveEaseIn, animations: {

        let center = cell?.center
        let frame2 = CGRect(x: 0, y: 0, width: 50, height: 50)
        cell?.frame = frame2
        cell?.center = center!

        }, completion: nil)
}
Run Code Online (Sandbox Code Playgroud)

(我从这个问题中找到了很多代码示例: UICollectionView:选择时动画单元格大小会发生变化,但这适用于单元格选择.不突出显示.)

所以在didHighlightItemAtIndexPath中我将突出显示的单元格设置为新的大小.大小设置正确但出现以下问题:1:它没有动画,2:它移动到位置(0,0)并动画回到中心位置.它根本不应该移动位置 - 只是尺寸.

我在Shazam应用程序中看到了这个效果以供参考.当您在歌曲名称下方的按钮上对一首歌曲进行shazam(或查看以前的shazamed歌曲)时,可以看到它.

Ann*_*awn 7

UICollectionViewCell子类中,您可以使用下面的代码.我建议不要使用touchesBegantouchesEnded,因为覆盖这些将禁用didSelectItemAt委托方法,UICollectionView因此您必须通过自己的委托单独处理.如果您didSelectItemAt在视图控制器中使用委托方法,那么正确的动画方法将覆盖该isHighlighted属性.

斯威夫特3/4-

override var isHighlighted: Bool{
        didSet{
            if isHighlighted{
                UIView.animate(withDuration: 0.2, delay: 0.0, usingSpringWithDamping: 0.8, initialSpringVelocity: 1.0, options: .curveEaseOut, animations: {
                    self.transform = self.transform.scaledBy(x: 0.75, y: 0.75)
                }, completion: nil)
            }else{
                UIView.animate(withDuration: 0.2, delay: 0.0, usingSpringWithDamping: 0.4, initialSpringVelocity: 1.0, options: .curveEaseOut, animations: {
                    self.transform = CGAffineTransform.identity.scaledBy(x: 1.0, y: 1.0)
                }, completion: nil)
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)