animationDidStop 不执行

animationDidStop not executing

我正在尝试获取我正在制作的项目的背景视图,但遇到了一个奇怪的实例。

我的代码是这样设置的。

import Foundation
import UIKit

class MainMenuViewController: UIViewController, CAAnimationDelegate {

@IBOutlet weak var colorView: UIView!

@IBOutlet weak var startLabel: UILabel!
@IBOutlet weak var firstButton: UIButton!
@IBOutlet weak var secondButton: UIButton!
@IBOutlet weak var thirdButton: UIButton!

let gradient = CAGradientLayer()
var gradientSet = [[CGColor]]()
var currentGradient: Int = 0

let gradientOne = gradientColors.lightGrey.cgColor
let gradientTwo = gradientColors.darkGrey.cgColor
let gradientThree = gradientColors.veryDarkGrey.cgColor

override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view, typically from a nib.
}

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

    gradientSet.append([gradientOne, gradientTwo])
    gradientSet.append([gradientTwo, gradientThree])
    gradientSet.append([gradientThree, gradientOne])


    gradient.frame = colorView.bounds
    gradient.colors = gradientSet[currentGradient]
    gradient.startPoint = CGPoint(x:0, y:0)
    gradient.endPoint = CGPoint(x:1, y:1)
    gradient.drawsAsynchronously = true
    colorView.layer.insertSublayer(gradient, below: thirdButton.layer)

    animateGradient()

}

func animateGradient() {

    if currentGradient < gradientSet.count - 1 {
        currentGradient += 1
    } else {
        currentGradient = 0
    }

    let gradientChangeAnimation = CABasicAnimation(keyPath: "colors")
    gradientChangeAnimation.duration = 5.0
    gradientChangeAnimation.toValue = gradientSet[currentGradient]
    gradientChangeAnimation.fillMode = CAMediaTimingFillMode.forwards
    gradientChangeAnimation.isRemovedOnCompletion = false
    gradient.add(gradientChangeAnimation, forKey: "colorChange")
}



func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
    if flag == true {
        print("animation complete")
        gradient.colors = gradientSet[currentGradient]
        animateGradient()
    }
}

}

我遇到的问题是当动画结束时,'animationDidStop' 永远不会触发。第一个动画 运行s,但当它完成时,它应该 运行 'animationDidStop' 函数和 运行 'animateGradient' 函数在一个常量循环中。我在网上寻找并寻找解决方案,但似乎找不到。我是 运行ning Swift 4,非常感谢任何帮助。谢谢!

你遗漏了一行:

gradientChangeAnimation.delegate = self