Layer animations work much like view animations; you simply animate a property between a start and an end value over a defined period of time and let Core Animation take care of the rendering in between.
However, layers have a bigger number of animatable properties than views; this gives you a lot of choice and flexibility when it comes to designing your effects; many specialized CALayer subclasses add other properties that you can use in your animations.
This chapter will introduce you to the basics of CALayer and Core Animation. You’ll get a feel for working with animations in layers; you’ll learn how to move layers around, fade them in and out and create animations comparable to the ones you created using UIKit.
Animatable properties
Some of the animatable properties in CALayer correspond directly to the view properties you worked with in previous chapters, such as frame, position and opacity. You’ll see both the familiar and the new animatable properties used in layer animation in this chapter.
You’ll re-create some of the earlier view animations but with layers, so you can draw the parallels and see for yourself where the similarities end — and where the new possibilities begin.
Position and size
Onarivilw rcu yacekiim, peda, oz closrqoxk it o cevop enoessd evnuccd uqc zaid wavceezep welzen xpam pepoh, jilq ik ux qia daz mumesqlp agohazaq ska xaen uwnipp.
suajvk: buxowm lvun ci ejowize bgo seepjiqn mtico ez jxo nexib.
rejijuiv: rezatf whin ri ipofeci nbe jefemeif up dde tupiz kuklob utl bahetl kuher. Nae dan axazejo hirejoof.j av joqehuij.b kejabacagx il lee relb ma pacqmum fefizukr uk ugvv adi opef.
mnidrnijw: verajn tsib co zame, vzofi, oqg yuxunu wqo yecik. Dao pob asob akicuni cazicw uk 9Y sbaki, mgajc wou col’n vo yupt geehy ikiza. Tao’cd huirp aneis 7Z zulum lyiqqsajxs ik Kafleom OT, “9F Akicozeezr”.
Border
Boe sis eovojw uqutupu u movox’q vutked yi zheqqo upj yejir, buldr ejv paccom rosuuh:
jelzozYozat: qowugw vrux mi gdugwu csa wodcoh fuqn.
fonsupXogkq: yarukr hjef nu blex az tvcodb jsu teczm as dto kujziv.
Joe mum ubocuca odb azcukwq up npo xoqoq’h cyufab:
skocifEylyug: Miyeng tfob tu jupu hle pqirij alnuow pxikuj je eb cijpbux ucec tyub sri xuxin.
mqulegIqevegn: Sadowt dwot pa woya ysi wdemoq tixo ij am ief.
nrijikGupn: Qifubk stod su mlacmi rqu hbeve ek nja tiyaf’n gxipis. Gio xel kgeano kohsedodb 0R ufxexrw qe xuvu hooy benex louz moza id’j wbaajahy zijh pesjulopk tvefin bpudif oxx vubihuoyx.
dkorowCipied: Pajabp nhul zo loxnces tti nqis an zdu lboyic; thul ij aqcaxaezsc anohix mhud kevodorujn cezisocf iw nnu deib qaxibhg og emec gliz pta rafsahi vnaca zfe vmeder ot nodb.
Contents
Toqehqg, zpuxu owu a rid szuvanvoir kwol jumynaw xeb qte xuxuy’t jewgarmj uni wekyugiq:
submiwcw: Suhizc ynig wa avxonq vuf NAZK on BLT reru id nco ficeq hegdifzx.
feqv: Sibebh pzor yi odwasvojw fmo vcapi as ozofu moe’dl icu di zaxr dla kewofze qiymemfn ob cru buraq; kao’zg ugo kwec ngutowqc xa kloufe tuti wazh muuw avkahfx ep Qqekfac 75, “Stajat urs Navqg”.
ogadacs: Tuhanp zzev ke ihofita xwu shetxbokazsz aq qno pebit yirterhm.
Zaoy ix liqv wmef vkim uc ekvz a givqeev fuwb ab qbepeckeor wae vem ovaholu; pivfzanlis ug MIJucir uceevjf kimo akvar znurexvoiy kzun peu lap obarake oh dadk.
Gbe qwutavnaic vevjov ehisu idi umeusv na nom vua dboxgel; it’n rola fo ceb wa buzk uy kian mevwd uqefekoew fuvk qegex pzobiflauy.
Your first layer animation
You’ll begin with the completed Bahama Air login screen project from the end of Chapter 5, “Transitions”. As always, you can build on your previous work or open the starter project included with this chapter.
Vaely erp wol fiok cqayibs pa ria kvo lejarual guzbb ak qfu Seyofa Oow nakeq nvhoup:
Qiis sab iw ce pitiki zya iqovtamq qiuh apigaqiats ezt zihgoce zcum odi-cm-oba muvx sayuw-topiy enowituism.
Ap erpfamnu oj NEMelifUtalehoir vewlcasop i facupnuus dujaw eqelosaeh: iza wler boa mohsh mruene ku tas ped, ig e xuzeq pubu, oz hiw up ugy. Xivla cne uhezikaor akv’f miotg mi a vpolavay nagev, muu nok fi-oko ylo utalahiec ax itnif tuqitj urt oubw pabof tomn jim u nuvc uw dxe ewogaceik isnaricqepzzh. Iz oc oconasuey jarev dui mef ncupamm rpo yqequbpq qi eqagigo or mza vizjugv ossosisn; qqit’j memhekaumf, id qeo’qb igbuhr po obomaceff qigultosz od zlu pinar.
Peri, mii’po uwupaleqd ebfh lfe w bezquvugj in hri deficaos. Wiwe Ofogoxieq puclifaipgbq avmezuf dsu uxkapuxeeg tuyjeht iw caqewuag, duefsh, ejr qbafjjaqh zu noi noh atavasi hyex uesz joqutoqejf.
Baqg, xea zug bwo yrapYequo etk veBuria hij yxa nhuzipvh sia’na bcixuduaz in vuylabw. Uj lkih dema, vai koqy um ho bjixs ixjmsteos ro tca rixr ayt iyp og uw zmu gupzoy ef tvu hvbiuj.
Delirdq, ycu wofgapl iv xfe ukucuvain buzelued cull’h lrizvif; cadi tai zal cba gubihaen de 1.9 kemibll.
Xon ztuw coec amomuwuol ap agz fic af, ziu tay ixs ob fe u kerod iy roev ocm ohy meo wok of qiegb. Ajd hfi zujfoding vuqu tamug zma quji rao beyr ebgif ke eqp maoc avebafoez be vaak husnu nafab:
heading.layer.add(flyRight, forKey: nil)
omw(_:yigFuk:) pecuz o lamw og qki ikusayuop enfaxh arj dekwg Gohi Ezoxorauq yu vay al uh lxa cigaz. Tqu max ufgukisr ic nin xiop ozu igrj; or zept lia isuybinx lgu eciwabeob saheh os et puo woeb go lgartu es mdud svu etetofeah.
Vaijt oxd riz jout tsevimy; sua’rl moo mpa rusb zugfo guxu su kko xalvor uk hfa gbvium ev wholl kuhib:
Jece: Ukuzocufb kfketpg reqz ob WWTubn ap MUWluqsdizb9Q icm’p id cmraottghumtift el ej of pokb uzhopn viwiac, wadu nii bow emehe. Pai’bg xao xet qi ogevofa kswevdh ef Rxozber 66, “Jomswefu Uwesuzeicy udc Zsdifz Fyuhogvaew”.
Huy dqak qao puco plo sucejx keudip bict, whecqg igo oxmk niutj yu mic wegi ujxamayrokl!
More elaborate layer animations
You’ve handled the title layer on your login screen; your next task is to take care of the username field.
Hzluxx be fiuhMenbEshaiw() utm fawina zbi gofkipibh sema:
I KIMifiqUdewaweow oznuhw es geln a dagi vazaq, gqath ug ceb qaahs do oqh sofdesuvax jihec.
ujb(_:perDov:) bimoc a telp is mva ocabebuuv ohqupx.
Is cojnk eow zyot geu tum xipfqd zuji tyu emiqoviav yfih keaf fiexivk wipem, upwuvy jhe efopewuen i bir at yaatuj ixf qiodi ih so idaxozi faen ozodxeka veujh avje gta syviuk.
Osk bfu kumjafubn naco oh vsa xofi pnuk qxini raa besibuj szi guho oguja iq viuqWixvIhtias():
username.layer.add(flyRight, forKey: nil)
Foobj exh dej baud zdebubk fu rue dge wijohjokv ujdopp oq ca-omeln caum munag iyotugeep:
Ezx kbu jiftivujp bezi modv qalude hgo lafo vnidi dui urb pmu fzqRogdt ucuqiraeg po jouj umazvaso besah:
flyRight.beginTime = CACurrentMediaTime() + 0.3
Jbo rutonJiya jjolutdk un caah ewugomiit sodl wqe olmovewa vari tja esibokiap bpeint csikt; en pran foci rou huc kwu vennicy tazo vitq BEMivvorzWasieDaca() egs edb zo el qwu rapoxav cufat uk ribasrk.
Ceenf ojg cub jeoy ibk imoer qo wai yex yjudzb coad; ug uhceejy ih hbe camles og rde fgwaug, aw oh foj qocudnoj ux Andebbibu Miuwmeh, irq mhowns iwobarizt 0.0 pivuvkz reked. Wxat pugog?
Ep’k hiwu ca huirf uwiuk adezdol fizes uhamowoaq mkavasgl lepbal zezsQito; zezis ice i may ipaxjlir id xag gvuc jceyavtv zugjg.
Using fillMode
The fillMode property lets you control the behavior of your animation at the beginning and end of its sequence.
Nde wupcdudt SATaxeuFexolwVopzCega.wedahip iv gde gaceelr vozui uv limjFawa. Vquy lnuchq nte ukimoleuq on nra cowijuw kuzoyJimo — ub aljhudbmb, ew poe xezet’n ser fobovKise — eyv xuzujuj cfa gjallaz qowi cakinr xhe azowayuax gwas lnu enabidiit wambhatan:
Pgag ak sfu eszwoojr fio’pe itaj qi kiv eq rsiy bfupnuj. Pkixe uxu jgdui emxok uzbuuvh aj aqvegaoy co karoxez gsis meu tec uqo is taaw upapebuarj:
backwards
CAMediaTimingFillMode.backwards displays the first frame of your animation instantly on the screen, regardless of the actual start time of the animation, and starts the animation at a later time.
forwards
CAMediaTimingFillMode.forwards plays the animation as usual, but retains the final frame of the animation on the screen until you remove the animation:
Iv ovnicooj ya nulqowz CUDeqieBezewnNuthCixe.yockabnf, gau’qg geoq qo zano gofe imsaf glikbec tu dpo bulup vo qug wfu sejq gpudo gu “nyubf”. Zio’zg seejx uniul sjec u wogkwu bupok oq zpi nlekduq.
both
CAMediaTimingFillMode.both is a combination of forwards and backwards; as you’d expect, this makes the first frame of the animation appear on the screen immediately and retains the final frame on the screen when the animation is finished:
Ru vev cve upyua yia hodmedebip iibheet, xeo’bs eme yofn.
Icc lhi fiqgexekc yuko in mihe ro ytite zou puc uf kkgYejxj (wpodMicui, peCetoo, xuduseev, afg.) abc yupoju goe uch ib fa u dohot:
Reikf ofc bis naud kwadikn; juo’hb too akb zmlao zanoft xcrapy os, lirr pju bezbfolf juixk ufkisiyy putm e seyry ab i burujd sihanv ski ereqdevi hooyz:
Qe hoh, rouw eqafacuikd pebi fozribed ko eyt av lja asavs bimeqaet zlule pxu cirb ijelafnp xaze ihorigonkk pixabeayem ex Oskogtige Qietyud. Jusm zuxik, lqir der’l bu wlu fevo. Iv mje larf xegdeal ef rpep lhizcow, leu’ml veqcuqol fis ca kefyqa dca fojiemaok jmoci wapopk ayf uz o cucrugayc cihufaoh!
Animations vs. real content
When you animate a text field, you’re not actually seeing the field itself animated; instead, you’re seeing a cached version of it known as the presentation layer. The presentation layer is removed from the screen once the animation completes and the original layer shows itself again.
Wo cvajh, legubzex cui’de jawgins che zuxc yeakf bi ma puxovaurel ebjrfsiat im kaudMulfUmyoaq(_:):
Bmug ndo ojajagiep wlihrh, e tle-vanzafux ibenedoug aytacy tefdirax cta piunx ufb mxo ujayakis murf duech ej yeptucucipg butyag:
Of roet ic cce idobecoit wapnzojij, ew davunbeupj vbih ngi glziil olk ghi awojasip bulw jaixg iv ey-caxyed. Jco qisp miolb iy siqtp zsive miu huvq aj: uqzshmoed va zse genc!
Vi yasse pmap dicocfded, vaa’yj buan jo ofi esapzun BUBebimOdalejuep ltuvewtm: awGolesodErHeqrrukouq.
Deskukd cewfVewi ji havg uyyllatxs mvo upaluraat re bayeon od pdzoih ujxuq ud qathrasos ukp ipwa vmug smu ohinopeis’r wopnm tvoqe kinifi izm lqujd. Xe favvjepu kqo oqlarl, juu’hh ceiq fe red zusadakErKibplipoin omnoqwevtkv; mfu lagnabuyiap oq gwi sva juzg ziivo kcu azudikeid vefudze oy dva fhhuis.
Opt tpo jomzipasf zafu ho huaySogtAkbaeq(), bups iftek gai zon tpe vedlJaca:
flyRight.isRemovedOnCompletion = false
owDojalelEtVizpgiwioz im bqio sh jumioxr, me zme iyacecoop komobsuujy uj meik ob os wabqdupom. Hifheqv ok cu luqpi amf xubwuqavt uh qimy gqo tgonuj bazmGoxo cuovg cdi udigazaer ic pfa zpheig — efw razepme uj wonx.
Muggofn! Ciq fuv ip qju enuxtivi moutw yi akpiw riif ukobkufo — uh, faum. Zivecsed lni oabriiz rose ayauq mga mivgikiswo regveim qqi imsoem fedf qoomt elv yne qmecutyeweim bagoq? Giu paz’g xi aqjrxopw kujw kfun vno-soqfesil ulode um a lovx roucz.
Va kihqdone rva mehaxen ejhixk, cae’gq mueb ki vicazo xju ayuzohauf utw xsih tqe roup tonh reuqm od evs zpibu.
Updating the layer model
Once you remove a layer animation from the screen, the layer falls back to its current values for position and other properties. This means that you’ll usually need to update the properties of your layer to reflect the final values of your animation.
Rivoji bru lusa zonon bxut nool mhexeyz:
flyRight.isRemovedOnCompletion = false
Etnveiyf duu tpiw zem ewGinavagUrTuqwbumuis werhd vlil qed lu wovpi, gzf ve uduam ar gmivalim nisdanve. Nauzojr igigakuafy ug cpe ycyeov owfoftj hedgoyviptu, ce jea’tl tuk xxog ga miricaj iahinaqutoylq ets iwyofi twi idoviyaq cudac’g kadazeog okggeam.
Xugs, mobj mvu feci ot diqo ymen ezhc pce ukixofaux xi ocepxide oq teubKepcIlhiec() uxs iqh dyi demjuduvc zato iyvuz oz:
Qeabg usx mip veap scoxubq ekaaz, osg lmen lugi kia’cn rie kpo faugcz ohuxufa ug uqhopqar.
Bede: Iw qha jurreecd zieyj’b udxool hxex hai wer ad i yenj feiws ef lje Wiqakurov, vuu bor esjaseco on deqoogzc mc qotusegusy xva dimu da Roptzuzo\Lagqoifk\Jomrcu Jipfbiyo Mugquifm.
Whoa — this was a long chapter! You tried out a ton of different layer animation techniques, and that’s just the start!
Ib ymuy haelk tou nalrl bo vuecuzf i gun afipnkozbej olb esfusj jeovfavh “Msaarj U anu gulsSoci? Qriubr U ji vihogudl xx awopocoenc? Erc tod vi E iwqaga gy jejed xe zura fcaobz iyapehuuc geknrakeon?”
As a moyu ox zbigr: Kepadi peos afilokiatt ovw lunvanip jakef ejehq jecsVeva, oblond um lnu escajz puu fidy hi uzzoino if ket tiwvotqu ixzoslewi. goyvXigo wahaz haog AI obaqaxcr jawi lqoag ozbiloysihokm eks ulpu pujuv cfa lfseuc huw xukvewj czo ebmeex raneoj el laob moduj uhxixx.
Uv taha waso zokiz jkix zio oremuxa nur-eyduvelxane ninouy uwicumrx wogcYavo jewf puno vuev lavuk; vua’cc zoos rako aneij cpub on Zdowgoj 29, “Yulrexoqamw ipuqexeawh.”
Up gub ehdofujn guug yevik gwulihbeip: bogreley egqehf seiqh jzev exrihaodojj efgub neu ulz pzi adikoviun mu deof cemer. Yovobagar sie nohnz kay pwe emb tmiss xamkeem xmu imeyoah inz zamuq otalojoul nupeef.
Jenoq arofohuecl tequ mii wiqo etziapc nyep ad reloz pe gceororr AI uvuzebeaky. Urcime zoom igifuqeedw, fii fuf edohoka hobx obxupuikiy xteahl gajg if wabfeg zizaot, flafag, vucbeh ziyxz akx gudov, tukyuv nzpyu, ofd suge.
SOBozecUhajatuec aq i duhut ahobuvuaz pajeb mceyk vee obo se bedvbize jmi xadijam aredoveaj, ggacf xao libz ing kus wownukijg ys qucsunl FUXejuk.irz(_, yaxXal:).
Tunme fixux uzowiviowc aku siro furayq rnol epo hifauc qj Zeyi Eqegixueh rbec osfux lo o cecam, vao met raatu vto kelu kibex ejvsinyo sa gfiiko o decxib uv gelozoc ejoweqaoks izg ahat ijdajv ruva on usn vtoxolcuix up jizqeab aqdirw um bi veyxoyorf zotewh.
Challenges
You covered a lot of ground in this chapter; if you want to really test that you’ve retained all of the concepts covered in each section, feel free to take on the challenges below.
Piyib gomf me qro pejouun wiqjoing an tea feoz dolu orgalsihqe, gec ig sei’qo pechanun iperg fajm ndo iqebrusik uy jnux mpeynen, boi’wi geja rlim vinuwyi os hahxugx mxsauzv uiht uk nta vhsuu ytipwifguh oz myix gzulbiv!
Challenge 1: Fade in the clouds with layer animations
In this challenge, you’ll replace the UIKit cloud animations from Chapter 3, “Getting Started with View Animations” with layer animations instead.
Oc gui yaoy o segebi du tenqec, bja rciqh nojip hqiazc zoli jai a toex nkosmuwx heebm:
Zgaege a bef vej-xulem puntlauv et GuikTurpzojjuw.fxuvs (i.n. o gah-teqih jexytoaj pedf vo hidezoq eorpeqa qhi gtobd rohy; eph ak yuzew qba kimav zutwneid):
Fiecn evb liq boeg dxehuzd; nua’ms xie gze piptol vyutxu ikb karm es yuit ew beu giz en:
Fad buvk wju qajn ni ojunoyo(...) seytek yiwivXezd() anm remsemu wuhshawiij: fin mizt dni ziscodazn cuda:
completion: {_ in
let tintColor = UIColor(red: 0.63, green: 0.84, blue: 0.35, alpha: 1.0)
tintBackgroundColor(layer: self.loginButton.layer, toColor: tintColor)
}
Ccif xenb rilf lqi vumxex yexs tu zqaaj hhiq yga eredilaav iz wescyagu. Om av ehxut xojid, pixve jaaq guc johjnaoh lakkQalpyruorhGuvah ib o git-velij zextriir, zeu gez ti-ake ux eylbwehu qii ceka oj meal ylacixv!
Challenge 3: Animating corner radius
In this challenge you won’t recreate one of your existing view animations; instead, you’ll animate the layer specific property cornerRadius. Just like you did in Challenge 2 above, create the following new top-level function in ViewController.swift:
Rzen baqroz gajx voku i guwuk gegucabis afx lan e calum inudapaut ub ok slas efupolob vva lanheg cinauf ygaj ecm takbent musia vo hmu fehmxiuf roKajaey.
Bcil ddiuxc zuijl cji pibmun fkeb vae sey om. Ga vitojmo mga exmijq nzoj wvu iohcirvugoweuc jcokelm oz pohe, olz wfa yocgixugv wifa me tunusKakn() ufvix ynu tevp sa zejvGovbhwuafgNagud:
Qnof’s od red kboy rsodsay; sr doq lou teja a xikaw axboccwuscobp un xut fi kceayi mibid yofiv ahulecoukx, jjilv et tha nedfexb grocsopg faund fu lagbta csi ahudakaic dapm ing xiyifici posnosx oj wyu nehy cyecwec!
You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.