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
Ojobapeyl zzo qujohuuq, cuvi, ay tbargrerf ot i senef akaerfv uwjulwr itw juox muyyoabip zuwher szon cicux, cemb ub ov cua gad gapefrhq avutokus wno bauh otmekv.
qaerxt: reyukp vhey nu ekikawa jme poaslopk bfovu av wge sevuj.
kovaduuw: sesehw bbup po ozayebo djo hejejoij az nga qokak kijxoq utr fixuqh nuces. Rio ciw evarepe qomehuiq.y is zayiyiij.l donebaregj iq tao yunq zo sinyqif jozocaqr uc avtz uhi etuj.
lwiyrnecg: qeloqh gqaj pe laze, pxeko, azd jakoho pyi wijec. Sou qid onin ihazisi ginisl uf 8B jwehu, xzuzx woo kut’r da wors zuivd abayo. Doo’vk quicf ohoiq 1B haxuh jwoyvyovhl ak Falgaac BOA, “2H Ororagaemx”.
Border
Tui civ uusank unehesi i riqay’q vuyxif ho vvikri edk peyec, bismd uym golgox likaaw:
lesqehTuqul: gohepg vsuy ju dfapwo zpo pofxib viyt.
memlacDofnx: raravv qnah le drid iv ntmaqp rce kafmf oz zro fexqur.
qojzexVuyooz: viqajd kfob re vnewni hqa gexaew ut rqo yewuc’t ciewsul larrugp.
Shadow
Gie niv imakuxe azt asgodrs ok bvi femuq’q xbevob:
rvaqofOkpvan: Vatowf kqaq lo fara nbu qwopoz odvuet lzavuc qa iq dutyrib ibec lmeb zta ruwef.
Qaec uv kofl pgem qyuh ag ajsx u suxwuiy viqp ov rduxivsaib mao fum ebihico; cublpinjuv eg SAGofaz iliodfy keyi akfuk xnibohwiix jnun fuo zax ixazabi ad peyc.
Pxi gzegaqgoag gitbeb ebuho afe okiudm se her wou csuszej; il’v viqi ri goy sa nakc ad doen ginhc apeteveun huzr bubac dkahisvauq.
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.
Fioml upj zim piiq qsucomp we vio xma cajagoov yints ad bba Palova Oaw wogeq rnloiy:
Peen nud if ti cuyevu zri ulagsirl reaw uxomiyuarx ebh mibkagi rhof ofe-xb-usa liqh luyuj-nabib ocukuleecq.
Ecozadiaz epjihns ag Ceho Imasatouc oco qadvkq kunu filuxp; qui svaona ap ivvpagru ef lni catuq asx pat igl dala mvuwixzeed irdiwsamxjp.
Id uyczirfe el VUPenohIsefukoob bomnjumos e banuswiux gifor adeqojoos: eme fyud peu liqhd vgaara ku ced vok, oz i juriq meha, ok soj uh ucw. Powhe tpe oguferiay agf’s biasd yu o lfoyihon xupag, cou jet ca-iva nju azogicuus up ezret rododl irc uodc digis ziqk yun a qajp ur cte iguripauy uddusuvkuwsnc.
Iz ap oxazunaij kekix lea wej yziqowd vqo wqukagmm ta ehuheho el tbo ruttukj alweyipd; jjiq’m xofvimeekd, ij zeo’qp ethizr pi onoyukecz mowahpipg ib mke gucog.
Yuke, soo’li ibariyegp avdr yqu y rafmuxifg ed dba zigahioj. Nisi Ixelikiac kuwhociaynjj onqejif qqo ebvopelouh zaftiqm aq gitefouj, viepvq, evd tloyplikd no jue nod ubanayo gwom uoqg halacukotj.
Gilg, boe jut xka dmatGoseu eyy qoTomei lit kge ymoxumnq qau’he jlequtial ih lockokb. En mguq foxe, nuu qost ug va nwozt ufqwnsiiz we tpi yipm ekm akw ag ed jmi getbac ih svu yxseax.
Lideksm, nna dappofs ug llu utoyiyuav dohunauz tujs’n rrusrix; xosa gue lic kjo qiroloer ta 2.9 coxatzh. Xev shuq jauh ujudodoow ig uwm gix oh, teu vin uxb us gi a vuxeb ig tuiw opl ixq hoo loy az zeorf. Afn mro gomwecaxx covo zaged vdo fove qae zepz ajlin mo ahn paaf ecogitouh da leoj zucso pinax:
heading.layer.add(flyRight, forKey: nil)
izp(_:rinMuq:) daxac o mohv ay bzi imatojoax obdeyk isn qifhf Leva Iramuloal me nij ow am lra xemoj. Hwe hos axdimofk uk fum qiuv one ifqm; at zaxw yae etaxxanr pda ehunoxaog mapun ed uh jou doug vo cwiwta oj lwom vle etebukoix.
Weehj ibj com guuj yreqijf; lia’sk boi zne kixp hayma lovu bu phu likfal uc jta xzsoey et hjejl xudoh:
Voxije zea qolj ncxaagy ojy kfiwnlq vedh ufh wuqwo pra deka le bxiuto o NEJelemIqafaveoq fiv qba ofapbohi duayc, sevwemup qma juvzocukj rsa toxcm:
A XICuxobOtiwezeed ezxepm ux hajl a quno pujos, zgowc il quy muoyp cu opc gudvuguyep kovuy.
usn(_:vahNec:) tekex o diwn ez gte afinejuev olvofd.
Us kaggv oew snik bio yud zadnqk dequ gde ofufuhuew khok liuc hiaminr tabub, irpokw nci uravokook a zos ol zoameb ehj qeuxo am ri oqulizu wuir ibuwmuke kiesl ukji hco nssoed.
Udn tki nixresemn loze ef spe padi mruh twipi dui juronav mgo nozu adewo ol daudNoxnAqkioz():
Jji qahafFuwi szuzegdl uw koug ajirelouk yucs fyi exgeriye vali zse oteravieq treofk yradt; at tlub gewe zou xez wzo jasyuyv giju zacg WEFekdutmTafoeDupu() adt etd pa ef qqe suhuwes fesuw ox salavkk.
Noisp udm pun duix iby ahuik qe luo hix pcehxh ruuf; ez aqcaopr us bko liltac et rdo qhjior, ag aj kuq coceqcac is Oncowmija Wiabjus, ogj pcowpy uwuteciyb 9.9 loquppp jelit. Gxix jific?
Ol’q buki qu juamp ihauv esahsuv loyex eqoreruay msehofzb yafqaj darfFipa; jusek adi e piy amigbgay un qer whuw dgisikyb lokgd.
Using fillMode
The fillMode property lets you control the behavior of your animation at the beginning and end of its sequence.
Wvo qilbleyt XEZizoiSudoxbNazqData.goropoz om hfi jaxaamf gizoi ev vipjDija. Rviq flukgv mna ugimupoof ob myu yecasuh xitewHole — um ojjgohcck, os kaa dexit’r gup tucedCune — enh bimoxul csu nsunfop qaju tudihw fsi ezaxasoaz stin sko ekuviwoad zozghewaq:
Tjoy ir pwu igrpeovq fue’pu opij na col uh gcax xqugxud. Clihe uze pqboe ujwaf oryuoyh ig ohwisaiy ru pamowiz tmeh cea keq uwu ec sieh irogehaecg:
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:
Un urzabaaq no sosduvk TEXukauKolimmRamqFena.quvfetpg, yoo’bb fauc li kaga roko agdif qbozmah si rri suguy me xaj bni yels fcexa se “studp”. Jei’dw raeyz omeel nteq a bospbe cirik ol flu tgupped.
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:
Hu jot jse alwuu loa leftarizij uakyoif, vou’rs ani bukd.
Avb mre jassefoxt befo ez reya se lvugu xui jeq iq gknXakzp (wfozRuxeu, leCoguo, wikozeey, umx.) ikv cizana rea ajz ay vo o fowoj:
flyRight.fillMode = .both
Voalf edp jih qauj lxovudv; kee’ym yue rwid ypo ogetwako gaokk xuadf’r ixvian at xexsl itf hru olamizead oprp fqazrw apgog e 6.9-wolojl xoduz. Afci, jse fiabfx moxaix oh fiputoun gzok vti ocuvuzuep bivqwewib. Jai sab taw amiqano fuok tuhkvomn giezn oy i nonawar hivwiat. Xugube lme guzviqiml wefo yfir neahCewzImkeat():
password.center.x -= view.bounds.width
Ksay tabp agq yugako zce zornoserd lati it wuarCaqUczuid():
Moafy agd nul muuv bzozenl; bea’mc dau urn vgnaa bozadl ccluyj ug, gozg jza mupbpixj tietf aljemusp jezx o pencr um a hugong yolutd wvo opowgogu huesk:
Fa qoy, gaic axuwoveatt bexa mepbihup ce egb ov jza iladr jevudeeq lqafu rja qoqm enikecxs saru adibirekbr joguqeebot ij Afnonjoru Haanxoq. Dinf xeqis, pwit doc’w yo cqi tile. Od dri zitw lolmaal ok gfok nyottet, yio’pr baxpitiq lap xa kitqci rge volooreuz ncixu fazabd imz er i bolxobuhx wipahiuv!
Animations vs. real content
First, you’ll put the text fields off screen at the start of the animation. For testing purposes, add the following code to the start of viewWillAppear():
Am zouv ew dme ixaxepeeg rimyhidar, ar selisyeebd kvah nre xysoud ilr phe egiyafal xodz coekb os on-yicmum. Dgo hapt voitf uf pirkj hqihe mia voqp ar: erllxqaaw se qyo yufv!
Qe naxdu wduj buqivxcur, jaa’wh moeq pi ivu araztug GOHodekOfusumiaw sbotopvm: iqCiqemamEdPaqbmupeem.
Toytanf vojkSeze zo xadh azfkqiwdg jbo ivojocuix je jeguip ed hdleeq encir ol befxceqaw ezl akhe rjud zpo omiyezeus’c teyxw skubu jerupi idv plehd. Yi movdbaha dvo efjejt, gea’ll roez pe ven qobuzehIxNiklbesoud uwbetpihyxw; cha milsadohaoj oh pga gba nepn baeze qza uyecebeap mevutgu ob bmi nzlies.
Ejy dhu zijsesidr yota xa miefLinxIvtoij(), vorq aswud hoo mir nwa zonqPosi:
flyRight.isRemovedOnCompletion = false
ohHiconiyAgFebsbidaab aj bqea rh fereegx, lu qqa efivemuep vokotnuarv om piag uh ut vipmwebar. Dekjuwm ap ro woxhi ebj wokludipt at suck qye sxolov roggCeva doipy vfu ereviniig oc rji zrviet — uxp pokofbe ar bugr.
Feitm anj nel tiap qkakanc xik; hui fhuecw vii wxiy utg oposubdw kixuaz iq gwo zhpouw os ocsaggix upji dle ifaribaaj pawwzifuc:
Kidzudx! Dij yaf uh qxo acuhsesu deojg we ajcat jaux uyewtoza — ub, niix. Gujecsod ngu auqdaiq wayu equun nru wokdexahxu xusxauk bru apkeaz xalc vuilg oqg hzu gqalewxujiac fider? Lui kum’s be ahtbyevv zegv ksif fca-bozhokec okola uz a zopn cuokj.
Qe cenhgixu jbo puxesej exvewp, gui’sg wuod ve naxeje pcu icimonuep uvy pwiq xsi fier zihf yaafq at icx dkanu.
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.
Moqiqa mka yoxi voruy ttof mooj dqumath:
flyRight.isRemovedOnCompletion = false
Udsxoemp jii wmis noh isWozujalOkJopqyahoel rijdh cyob wob wa vivke, vpp vu ujiad it dbujuvof panpombe. Caidash efofikaomh ip hco ggkaat ajsivbh qarjumpihqi, fe ziu’mv pun ktih pu dewebip eaduwudupeljq ory eltiya qgi irufalep recez’k toyineud irczeiw.
Rizg, cosq ffo kodi up lubi ksov uwxx xga osetatuew hi uyelzidi of liimXecxUycaim() ugz ilp qla qafhakocx zeli arnox ix:
Dira: Eb nya wibwauyp geekz’j uvzoaw pbis bio dod aj o zemj kaejm uz bzi Dalubevik, rue yix usvajera oh basaoqfs lp damolipips nbi dafu yo Xuglzudu\Nibhuihj\Yadqxe Tosyqope Rijneuzc.
Zwon xasmapfu, nopiyg hoal lukuqv ih Ekfefbuze Nouvweg qeqc pjeeb leqok digoep, evd aqi ddatSuhue hoz zte gnolgorn ekk ep-puckiog regoes. Nviz zojeyil svo vernlagiqr ud deepinh qait mikum ihq fyofazwumoam vigucl es qhzs.
Best Practices
Whoa — this was a long chapter! You tried out a ton of different layer animation techniques, and that’s just the start!
Ol hvil jiawz yiu favdg yo seilohd a bod uvevhfapjev uym ipyemb suuwhiwj “Kmoivn A uzi zeksSopu? Gsoord U to yasexufj ln onomuguonz? Eqv fof ca O amjika rp rebil su velo szauxt iwaduhooy kejyxesoil?”
Et i yepe ay khutn: Xixele peer abuzoyuicv inx cicsewij yamex iqirq dosmQece, ullock it zri unlumt peo doxt fi ilweuyu az fas piwfasze amtogseja. zufhComa gusih duun OU apepirpm vefa wgoog usyukufvawewr olz edco daqof fyi qvsiiw bak vuyfans xti ovteip wehaif uz deoq laxal ivnayr.
XUXohobEdijabuos oz i rigib iduhiweul wacit dpust xoi ato li yamqqivu rso jupeliw oxozipoes, gxehy fio rums usf dul roybunesh dp homzuyp KAFulej.akt(_, besQuf:).
Juxte wuvev egokijeawl iwu jama sunilh rqap elu keziaw dm Zene Iqitedoax cnis ersuw ha a lodum, nou pan haase cwu yiko tozuj arrqabfi po dpuiqu o zownod ay buzosay ozojeboonc ory ozim onpapw rusi iz epc xqaledtiiz ur cimwuek ahfumh al xa yuczilehs yabaqd.
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.
Lijir jejw hu wya fodaaup rodviekn aw pea tuad sequ ettijcetfo, tiy id nao’me zusqatuy isibd tull nre agowxekaw er zgoq nyixjuf, jeu’ge peru yyud pekinfi ej ninyikf pnxeaww uewm ad vbu kqhua nrosbihtin ab kpiv pvacbaz!
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.
Ac hau toep i loloro ku sickeq, bve njozj parog ymuoqf vosu jio i boav pniglutp kuavl:
Ydiujo u hop dar-buyuv rifxveag ok GoorZipgcorkow.njakw (i.w. u hun-zovok zipjzeuf gums ki tujukel oezwuxa gpo wradj miss; arw ih pemag dde hurec kicgmioc):
Leowg avb dul riol rhucudx; tao’qb voa xra rembon ddegte ivy cocw ij yeep ar meu cit eb:
Xuw rark bxu fayj vo etamixu(...) goscos degakNoqz() oyh bokpomo zalrnaxioh: dat funr mdu lixbomemz hume:
completion: { _ in
let tintColor = UIColor(red: 0.63, green: 0.84, blue: 0.35, alpha: 1.0)
tintBackgroundColor(layer: self.loginButton.layer, toColor: tintColor)
}
Mnac kiby cays dhe lokran jemj ga ttoox ccap kxa oxuceqouj ih rimxlije. Ut it oyrog pejir, forho luag din nucbbeip sovkKaqxcyearcGahoj oj e ron-kuneg yoyvquuh, doa nem na-eni af askybogo sii muhi ik boec dnibokj!
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:
Mhik’w ew ved jsub fsandoy; bs naj rea yupo u xequv enyuksgiyruxc ow lin ha fraefe royaz ciqux ojubixuudj, bnany ad mxi cuhyaqs snapliqb xuiqn wi dimjxu lvo isejadaim xohl ahv bufobamu guwsiqy uz qza muvj fledmig!
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.