#14 swift animate 動畫練習(一)

Stephen Huang
5 min readJul 4, 2021

UIView, animate, delay, curveEaseOut, viewWillAppear, viewDidAppear

Photo by Jannis Brandt on Unsplash

參考appcoda 教學文章

為了要同時有auto layout設置,又要同時改變物件位置製作動畫,
所以需要將layout的設置與viewController的@IBOutlet作連結。

直接從設置條件按右鍵拉到viewController裡面,確認遵從NSLayoutConstraint,避免拉錯物件。

為了讓動畫效果顯現,需要先改變物件位置,等畫面顯示後在回到現在位置,產生一個移動位置的動畫效果

所以我們要先在viewWillAppear 將物件數值改變,讓他跑到螢幕外。
按鈕則是由透明,然後突然出現。

viewWillAppear 是畫面即將出現。

viewDidAppear是畫面已經出現了,在這時讓物件回到原來位置。

這時按下模擬器執行,應該就可以看到動畫了。

突發狀況:執行後動畫卻沒有跑出來!原來是我在拉auto layout習慣會把跟左右邊距離全都設置好,
造成物件的置中對齊基準雖然改變,但左右距離沒有變
物件還是留在原地,
沒有改變位置,當然也不會有動畫產生。

這時你可以選擇將左右條件刪除,或是一併拉到viewController裡面一起改變數值(改變左右邊界數值要注意正負造成的結果不同)。

— — — — — — — — — — — —

為了讓動畫夠有層次,讓三個動畫陸續出現。

改變delay時間:

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

UIView.animate(withDuration: 0.5, delay: 0.0, options: UIView.AnimationOptions.curveEaseOut) {
self.centerAlignUsername.constant += self.view.bounds.width
self.leadingUsername.constant += self.view.bounds.width
self.trallingUsername.constant -= self.view.bounds.width
self.view.layoutIfNeeded()
}
UIView.animate(withDuration: 0.5, delay: 0.3, options: .curveEaseOut) {
self.centerAlignPassword.constant += self.view.bounds.width
self.view.layoutIfNeeded()
}
UIView.animate(withDuration: 0.5, delay: 0.4, options: .curveEaseOut) {
self.myButton.alpha = 1
self.view.layoutIfNeeded()
}
}

— — — — — — — — — — — —

按鈕也加上動畫,在使用者輸入錯誤的帳號密碼時

按鈕會左右扭動,並富有彈力

@IBAction func myButton(_ sender: Any) {
let bounds = self.myButton.bounds
UIView.animate(withDuration: 1.0, delay: 0.0, usingSpringWithDamping: 0.2, initialSpringVelocity: 10) { //springWithDamping 彈力 1沒彈力 0最彈
self.myButton.bounds = CGRect(x: bounds.origin.x - 20, y: bounds.origin.y, width: bounds.size.width + 60, height: bounds.size.height)
self.myButton.isEnabled = false
}
}

--

--