Swift Animation 初解析

Ken Lee
Ken Lee
Nov 2 · 3 min read

在App裡面適當地加上動畫,可以讓使用者的體驗大大提升,但要怎麼樣成功做出我們要的效果,就得先清楚了解動畫的一些細節。

Swift提供許多不同的方式來呈現動畫: UIView.animate, CGAffineTransform, CABasicAnimation, UIViewPropertyAnimator…等等。然而,做出單一個動畫從來都不困難,如何完整地串連起多種動畫才是成功關鍵。

近期都在研究使用UIView.animate和CABasicAnimation,就來比較一下這兩種的差異吧!


經過這一段時間,了解「presentation layer」是我認為最關鍵的一件事。
View裡頭負責顯示的Layer,其中包含了model layer和presentation layer。
model layer: 即一般我們取用時,所回傳給我們的數值來源,其為該view內真正的屬性。
presentation layer: 負責記錄著動畫過程中,畫面所顯示的view的屬性。e.g. 跑動畫時,presentation layer才會出現並且和model layer分離。

取用view的來源為model layer

然而,當我們使用UIView.animate,在動畫過程中
我們取用model layer時會得到「最終」的數值。
而presentation layer則會得到「正在顯示」的數值。
值得注意的是:presentation layer只有在跑動畫時才會出現,否則為nil。

同樣地,CABasicAnimation也是,不過和UIView.animate不同的是:CABasicAnimation操作的只有presentation layer,也就是說,其實它並沒有對model layer進行作用。

因此若我們沒有設定:

animation.isRemovedOnCompletion = false

那麼在CABasicAnimation跑完時,presentation layer就立即被移除。所以我們所看到的view就會立即跳到model layer的屬性,也就是跳回到動畫之前的樣子。

CABasicAnimation跳回初始模樣

而設定:

animation.fillMode = .forward

則是決定presentation layer最後要顯示哪個模樣。
.forward表示顯示為動畫結束的樣子。
.backward則顯示為動畫之前的樣子。

✳ 因此「animation.isRemovedOnCompletion = false 」必須先設定好,fillMode才會生效,否則presentation layer都被移除了,又要怎麼對其操作呢?


有了這樣的理解,在實現各種動畫時,能避免踏入不少坑。尤其是在使用CABasicAnimation實現多組動畫、分批進行、延遲進行、結束後又需要delay再接續其他動畫時更是如此。

實際情況還是得親身體驗才會深刻理解。最近都在研究實作各種動畫,開始懷疑自己到底是動畫師還是iOS App工程師(笑。

如果你喜歡我的文章,請幫我clap幾下,我會很感謝的,謝謝。

Ken Lee

Written by

Ken Lee

Life is born to live, not to survive.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade