如何在Swift中制作动画shadowOffset?

我写了代码,但我不明白为什么它不起作用...

func animate(vc: UIView) {
    vc.layer.shadowColor = #colorLiteral(red: 0.9254902005, green: 0.2352941185, blue: 0.1019607857, alpha: 1)
    vc.layer.shadowRadius = 5
    vc.layer.shadowOffset = CGSize(width: 0, height: 0)
    let animationX = CABasicAnimation()
    animationX.keyPath = "shadowOffset"
    animationX.fromValue = vc.layer.shadowOffset
    animationX.toValue = CGSize(width: 10, height: 10)
    animationX.duration = 1
    vc.layer.add(animationX, forKey: animationX.keyPath)
}

@IBAction func buttonTapped(_ sender: UIButton) {
  animate(vc: sender)
}

有谁知道这是如何工作的?

评论
  • 普以晴
    普以晴 回复

    缺少几件事

    1. shadowPath
    2. shadowOpacity
            vc.layer.masksToBounds = false
            vc.layer.shadowColor = #colorLiteral(red: 0.9254902005, green: 0.2352941185, blue: 0.1019607857, alpha: 1)
            vc.layer.shadowRadius = 5
            vc.layer.shadowOffset = CGSize(width: 0, height: 0)
            vc.layer.shadowPath = UIBezierPath(rect: vc.bounds).cgPath
            vc.layer.shadowOpacity = 1.0
            let animationX = CABasicAnimation()
            animationX.keyPath = "shadowOffset"
            animationX.fromValue = vc.layer.shadowOffset
            animationX.toValue = CGSize(width: 10, height: 10)
            animationX.duration = 1
            vc.layer.add(animationX, forKey: animationX.keyPath)
    

    By default shadowOpacity is 0.

    最终O / P

    enter image description here

    编辑:

    如果要使阴影在动画指定后仍保持在其位置,请指定

    1. fillMode
    2. isRemovedOnCompletion

    最终代码看起来像

    func animate(vc: UIView) {
            vc.layer.masksToBounds = false
            vc.layer.shadowColor = #colorLiteral(red: 0.9254902005, green: 0.2352941185, blue: 0.1019607857, alpha: 1)
            vc.layer.shadowRadius = 5
            vc.layer.shadowOffset = CGSize(width: 0, height: 0)
            vc.layer.shadowPath = UIBezierPath(rect: vc.bounds).cgPath
            vc.layer.shadowOpacity = 1.0
            let animationX = CABasicAnimation()
            animationX.keyPath = "shadowOffset"
            animationX.fromValue = vc.layer.shadowOffset
            animationX.toValue = CGSize(width: 10, height: 10)
            animationX.duration = 1
            animationX.fillMode = .forwards
            animationX.isRemovedOnCompletion = false
            vc.layer.add(animationX, forKey: animationX.keyPath)
        }
    

    最终的O / P看起来像:

    enter image description here