一直想好好的把動畫的功能試過,但忙一忙又忘記這件事了,剛好趁著這個機會,就來試玩看看,之後或許還有機會搭配其他的功能,顯示出不同的成果,以下就把過程和成果分享給大家。
常用來執行動畫的方法有四種:UIView.animateWithDuration(_:, animations:)
UIView.animateWithDuration(_:, animations:, completion:)
UIView.animateWithDuration(_:, delay:, options:, animations:, completion:)
UIView.animateWithDuration(_:, delay:, usingSpringWithDamping:, initialSpringVelocity:, options:, animations:, completion:)
下面範例會分別展示各方法。
先在 Storyboard 拉好幾個 UIView,並設定不同的顏色,為了效果在呈現上會比較明顯
視圖可更改的屬性:
程式碼的部分,先把 outlets 連結好
@IBOutlet weak var viewOrange: UIView!
@IBOutlet weak var viewIndigo: UIView!
@IBOutlet weak var viewGreen: UIView!
@IBOutlet weak var viewRed: UIView!
@IBOutlet weak var viewBlue: UIView!
@IBOutlet weak var viewBrown: UIView!
以下是完整放在 viewDidLoad()
裡的程式碼
let duration = 2.00
let delay = 3.00
// 讓方塊透明度逐漸變 0
UIView.animate(withDuration: duration) {
self.viewOrange.alpha = 0
}
// 讓方塊透明度逐漸變 0 後再變回 1
UIView.animate(withDuration: duration, animations: {
self.viewIndigo.alpha = 0
}) { (_) in
UIView.animate(withDuration: duration) {
self.viewIndigo.alpha = 1
}
}
// 讓方塊透明度逐漸變 0 後,平移同時再變回 1
UIView.animate(withDuration: duration, animations: {
self.viewGreen.alpha = 0
}) { (_) in
UIView.animate(withDuration: duration) {
self.viewGreen.transform = CGAffineTransform(translationX: 200, y: 0)
self.viewGreen.alpha = 1
}
}
// 讓方塊旋轉角度
UIView.animate(withDuration: duration, delay: delay, options: .curveLinear, animations: {
self.viewRed.transform = CGAffineTransform(rotationAngle: 45)
}) { (_) in
UIView.animate(withDuration: duration) {
self.viewRed.transform = CGAffineTransform(rotationAngle: 0)
}
}
// 讓方塊變放大後再縮小回來
UIView.animate(withDuration: duration, animations: {
self.viewBlue.transform = CGAffineTransform(scaleX: 2, y: 2)
}) { (_) in
UIView.animate(withDuration: duration) {
self.viewBlue.transform = CGAffineTransform(scaleX: 1, y: 1)
}
}
// 讓方塊變放大後再縮小回來,利用方法本身的特性,動畫會有彈跳的效果
UIView.animate(withDuration: duration, delay: 0, usingSpringWithDamping: 0.1, initialSpringVelocity: 1, options: .curveEaseIn, animations: {
self.viewBrown.transform = CGAffineTransform(scaleX: 1.5, y: 1.5)
}) { (_) in
UIView.animate(withDuration: duration) {
self.viewBrown.transform = CGAffineTransform(scaleX: 1, y: 1)
}
}
實際執行結果