UICollectionViewCell Shake

If anyone is curious on how to do this in Swift 2.0 the below should be a good starting point.

let animationRotateDegres: CGFloat = 0.5
let animationTranslateX: CGFloat = 1.0
let animationTranslateY: CGFloat = 1.0
let count: Int = 1

func wobble() {
    let leftOrRight: CGFloat = (count % 2 == 0 ? 1 : -1)
    let rightOrLeft: CGFloat = (count % 2 == 0 ? -1 : 1)
    let leftWobble: CGAffineTransform = CGAffineTransformMakeRotation(degreesToRadians(animationRotateDegres * leftOrRight))
    let rightWobble: CGAffineTransform = CGAffineTransformMakeRotation(degreesToRadians(animationRotateDegres * rightOrLeft))
    let moveTransform: CGAffineTransform = CGAffineTransformTranslate(leftWobble, -animationTranslateX, -animationTranslateY)
    let conCatTransform: CGAffineTransform = CGAffineTransformConcat(leftWobble, moveTransform)

    transform = rightWobble // starting point

    UIView.animateWithDuration(0.1, delay: 0.08, options: [.AllowUserInteraction, .Repeat, .Autoreverse], animations: { () -> Void in
        self.transform = conCatTransform
        }, completion: nil)
}

func degreesToRadians(x: CGFloat) -> CGFloat {
    return CGFloat(M_PI) * x / 180.0
}

When I want to make my cells wobble I do so like this:

for cell in collectionView.visibleCells() {
        let customCell: MyCustomCell = cell as! MyCustomCell
        customCell.wobble()
    }

Swift 5 Easy like this

Enter this 2 functions to your UICollectionViewCell and call it when ever you want to animate/stop, ex: cell render

func shake() {
    let shakeAnimation = CABasicAnimation(keyPath: "transform.rotation")
    shakeAnimation.duration = 0.05
    shakeAnimation.repeatCount = 2
    shakeAnimation.autoreverses = true
    let startAngle: Float = (-2) * 3.14159/180
    let stopAngle = -startAngle
    shakeAnimation.fromValue = NSNumber(value: startAngle as Float)
    shakeAnimation.toValue = NSNumber(value: 3 * stopAngle as Float)
    shakeAnimation.autoreverses = true
    shakeAnimation.duration = 0.15
    shakeAnimation.repeatCount = 10000
    shakeAnimation.timeOffset = 290 * drand48()

    let layer: CALayer = self.layer
    layer.add(shakeAnimation, forKey:"shaking")
}

func stopShaking() {
    let layer: CALayer = self.layer
    layer.removeAnimation(forKey: "shaking")
}

Help Source from Git


If you put you're code in a method called startJiggling in your custom cell, then you could call this method in your controller:

[self.collectionView.visibleCells makeObjectsPerformSelector:@selector(startJiggling)];

That ensures that all visible cells will start jiggling.

Then I'd also set some flag indicating that your cells should jiggle and test for that in collectionView:cellForItemAtIndexPath:. If YES, then call your method.