美文网首页
Swift实现上下弹跳动画

Swift实现上下弹跳动画

作者: 玉思盈蝶 | 来源:发表于2020-07-08 11:21 被阅读0次

    先看下我一开始傻傻的实现~~~

    func addAnimation(isAnimation: Bool = true) {
        UIView.animate(withDuration: 0.5, animations: {
            self.cartBtn1.frame = CGRect(x: self.cartBtn1.frame.origin.x, y: self.cartBtn1.frame.origin.y + 30, width: 36, height: 36)
        }, completion: nil)
        UIView.animate(withDuration: 0.8, delay: 0.5, usingSpringWithDamping: 0.9, initialSpringVelocity: 0, options: .curveEaseInOut, animations: {
            self.cartBtn1.frame = CGRect(x: self.cartBtn1.frame.origin.x, y: self.cartBtn1.frame.origin.y - 30, width: 36, height: 36)
        }) { (finish) in
            self.addAnimation()
        }
    }
    

    效果也能实现,问题在哪呢?就是没法取消动画。。。。。。原谅我不知道怎么取消,因为使用递归动画了。

    正确实现如下:

    func addUpAndDownAnimation() {
        let animatioan = CABasicAnimation(keyPath: "transform.translation.y")
        animatioan.isRemovedOnCompletion = false
        animatioan.duration = 0.8
        animatioan.autoreverses = true
        animatioan.repeatCount = MAXFLOAT
        animatioan.fromValue = NSNumber(value: 0)
        animatioan.toValue = NSNumber(value: 50)
        cartBtn1.layer.add(animatioan, forKey: "bounce")
    }
    

    取消动画:

    self.cartBtn1.layer.removeAllAnimations()
    

    参考链接:

    用 Swift 语言写一个地图坐标弹跳动画:

    https://www.cnblogs.com/missingcat92/p/4662863.html

    相关文章

      网友评论

          本文标题:Swift实现上下弹跳动画

          本文链接:https://www.haomeiwen.com/subject/qyiqcktx.html