How do you create a wiggle animation similar to iphone deletion animation

前端 未结 8 2329
-上瘾入骨i
-上瘾入骨i 2020-12-12 16:57

We are currently developing an application that contains a series of icons. We want the icons to wiggle like the app deletion animations when pressed. What would be the be

8条回答
  •  心在旅途
    2020-12-12 17:50

    Rewrote Sebastien's answer in Swift 3.

    let wiggleBounceY = 4.0
    let wiggleBounceDuration = 0.12
    let wiggleBounceDurationVariance = 0.025
    
    let wiggleRotateAngle = 0.06
    let wiggleRotateDuration = 0.10
    let wiggleRotateDurationVariance = 0.025
    
    func randomize(interval: TimeInterval, withVariance variance: Double) -> Double{
        let random = (Double(arc4random_uniform(1000)) - 500.0) / 500.0
        return interval + variance * random
    }
    
    func startWiggle(for view: UIView){
    
        //Create rotation animation
        let rotationAnim = CAKeyframeAnimation(keyPath: "transform.rotation.z")
        rotationAnim.values = [-wiggleRotateAngle, wiggleRotateAngle]
        rotationAnim.autoreverses = true
        rotationAnim.duration = randomize(interval: wiggleRotateDuration, withVariance: wiggleRotateDurationVariance)
        rotationAnim.repeatCount = HUGE
    
        //Create bounce animation
        let bounceAnimation = CAKeyframeAnimation(keyPath: "transform.translation.y")
        bounceAnimation.values = [wiggleBounceY, 0]
        bounceAnimation.autoreverses = true
        bounceAnimation.duration = randomize(interval: wiggleBounceDuration, withVariance: wiggleBounceDurationVariance)
        bounceAnimation.repeatCount = HUGE
    
        //Apply animations to view
        UIView.animate(withDuration: 0) {
            view.layer.add(rotationAnim, forKey: "rotation")
            view.layer.add(bounceAnimation, forKey: "bounce")
            view.transform = .identity
        }
    }
    
    func stopWiggle(for view: UIView){
        view.layer.removeAllAnimations()
    }
    

提交回复
热议问题