本文內(nèi)容來源于http://www.hangge.com/
,僅作學(xué)習(xí)記錄...
需求:視圖由上至下出現(xiàn)漸變色,點(diǎn)擊視圖更換另一組顏色蚕愤,有過渡動(dòng)畫效果。
代碼如下囊榜,有注釋
import UIKit
class ViewController: UIViewController,CAAnimationDelegate {
//漸變色
let colorsSet = [
[UIColor.yellow.cgColor,UIColor.orange.cgColor],
[UIColor.cyan.cgColor,UIColor.green.cgColor],
[UIColor.magenta.cgColor,UIColor.blue.cgColor]
]
//當(dāng)前漸變色索引
var currentIndex = 0
var gradientLayer : CAGradientLayer!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
//監(jiān)聽單擊事件审胸,每單擊一次就切換一組漸變色
let tapSingle = UITapGestureRecognizer(target:self,action:#selector(tapSingleDid))
tapSingle.numberOfTapsRequired = 1
tapSingle.numberOfTouchesRequired = 1
self.view .addGestureRecognizer(tapSingle)
//初始化CAGradientLayer對(duì)象
gradientLayer = CAGradientLayer()
gradientLayer.colors = colorsSet.first
gradientLayer.locations = [0.0,1.0]
gradientLayer.frame = self.view.bounds
self.view.layer.insertSublayer(gradientLayer, at: 0)
}
@objc func tapSingleDid() {
var nextIndex = currentIndex + 1
if nextIndex >= colorsSet.count {
nextIndex = 0
}
//添加漸變色動(dòng)畫
let colorChangeAnimation = CABasicAnimation(keyPath:"colors") //keyPath 小寫 k
colorChangeAnimation.delegate = self
colorChangeAnimation.duration = 2.0
colorChangeAnimation.fromValue = colorsSet[currentIndex]
colorChangeAnimation.toValue = colorsSet[nextIndex]
colorChangeAnimation.fillMode = kCAFillModeForwards
//動(dòng)畫結(jié)束后保持最終的效果
colorChangeAnimation.isRemovedOnCompletion = false;
gradientLayer.add(colorChangeAnimation, forKey: "colors")
currentIndex = nextIndex
}
}