我正在尝试获取正在制作的项目的背景视图,并遇到了一个奇怪的实例。
这是我的代码设置方式。
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”将永远不会触发。第一个动画运行,但是完成后应该运行“ animationDidStop”函数并在恒定循环上运行“ animateGradient”函数。我在网上寻找解决方案,但似乎找不到。我正在运行Swift 4,非常感谢您的帮助。谢谢!
答案 0 :(得分:0)
您遗漏了一行:
gradientChangeAnimation.delegate = self