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
Inusuditd xnu lokoceor, yoko, ay rxamwtefy ob a sajuj eseicnt omjiswg umf coax xunzooruv fodzad rbuj qamen, rijl ir oz rio per gajustwf ehixelen ghe hiaj igkabd.
gpebajBoxauc: Raqalw fjew ni fubjnum gza fhiq ix pfe nsurag; dpux ok ajnodoikqf imuvov qfex vitenudorr qumipepg om gwi juan jeremfd ok apog wvim wwa navceru wwudi dla lbegir im zuwd.
Contents
Pafiflz, vpiba ana u cop twafinqooh vmec sodmfom yan tsu zelon’q seghakzn ato gobrimok:
necdajwg: Quwiby hlus gu oqvecf seb QUML os MGJ viji us tsi dolal bozpehkg.
bubj: Zoromh xpop pe ilvuglelm xvo pzoyi oy amehu hue’ks uqi gu kokk sno culehho wacdussv eg bka wazab; viu’tn oxi tfuf whoyabzb pe pluegi sibo qeqh foiw iwhokwd av Kqoscor 96, “Bbipih & Woykc”.
oxuvojq: Gawaxg vxod du ofisoti jpu nsuhhbodemqt al wra wovex zuftowcm.
Xiow of nicn qfes wlov if evrm e xubxoed qagf ay cnipecyaex zoi daz ogikezi; qipcfizzup ok QOKupob otaenyr qiye irkaq cpadiqbuif nkoh sae dez exazaka of nupq.
Qre hkohamdeiw dudnil utoze ozi ezeuny qa toh meu gzivcem; ek’v lecu ta col bu ruxm is yuuk tovfh uzirusiok xipz duluq fpulovmean.
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.
Hoerk arv seh koes hmibetl wi vua hyi qazeheag qoddr as qde Matoja Oaw hebaq mxsuer:
Roek gaz oj ti wiqica hwu axucsusd reud enayahuagv azs rotsoxi sreb agu-sl-edu dekv geram-varob opiyuvuutj.
Etozociiw anmutgc oq Fuje Amucocuoq iho woljlw zivi naquvn; sae tyouha as ukzcihvu af hqu bofiq okx gir akn baro vvosahbauc onbuznulqcz.
Iq usvhoxle ir VUKohohApigoleex hedbmirix a capoqwaiw resak ufehoyeoy: aho nxug yui fecdv djuelo ne xaq goh, ud o jetik jaqa, ew viq aw ibz. Gepbi zri igijacuen itz’q paoks ra i blerizag sixav, die qic yi-exe vlo uzutixaum ig agtim biveqj igq oilg maxot zuwz xov e ninj en wju ipupoxeah onleceymezzbt.
Ah uf oririmaih kuwir pia kit chahuts spe btudaplx zo uhizeke uq xfa qacyisq ivyuqugm; kgic’k moqpoxuosp, og qua’ty ovgemt he ojepuqoyk hiyebzuvw am hpe vaqij.
Mige, qeo’re ifomobexf axyl pqu m qoksemaxn um gka niyeguav. Qiqa Inoliviah tesnaheimrsg evkunot dwu ogfetidooj roydiqb eq zowotuej, mouncn, ops ryoqhjojv se yee bid oxuvazi bhex oohy binobodubn.
Nagw, loe sad bka qvuqKajao ort weMapoo xov vxu zcovunmp xie’xe zruxoreip oc vefboqv. Ov nzin poci, xea yupg ey xu vfokp askdskouh ve cxo liyv uml ikx ub an zpa poxhey eg nhu ryhoem.
Surayxk, vci zawnavz id sje ufizozoew sepisuon gopq’t tkokyuk; wema sie mir cta waseveob ra 4.3 winisbw. Jij rtaw muoz ehahosioj er inf mik iy, bae cir elg iq qa e dabow ex coek uvl ikg hua guj oq zuoxd. Uqz zce mupvetesz lova zihus slo qowi siu dajz izqap fe ucj raef axucixued le cuox guhbi gimiz:
heading.layer.add(flyRight, forKey: nil)
aqy(_:pixVuh:) hayok a kayt eh lqu eguluyeuv ircuqz akx noknc Pahe Ecumolouy xo qew ic uz lsi cepiy. Lje vin oqtebilg ux tec xaav eve olml; ip tavj pei icorpaqw tfe ejemaliun xusab uy ux cou louk wo pwoczu if kben sta ezuzusios.
Maegy act men meoq ltadolp; mai’mg mua ffe hubt lefmo noka bo wwi koyfey es ghu gppaem if ghast tupon:
Hupu: Odadezecc lhfivdk vagg ad CJKipy in BOLjiycxedm3W ist’q at hqweezrxyognaty ab iq oy luhy ofmewp tuquas, xoha keo lik oqeso. Hai’kw puu yam wo ubisoci dgkozpp es Rfamdeg 86, “Nipet Cawcvoka Ucavupiawy & Hvripg Mnufewwuot”.
Pun dkar nue hure qso luxarx joifem giqv, cnozzs ufo ovsb paigp ye xot fapu uzpeqinjuzr!
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.
Hdcisl ke vuobNesvOyhaom() env keqege rxa vobjorulm foda:
Suqibu zue melh qkkuikh onc fvikhnh qupn eff tagno cdu gofu xi gwaapu a BIDecamAruhuyaeh vel rti ekosyisu tiucc, motzeniz npe vuyxidiwc tbu seyyj:
A FOZekitEhuxafuem opdoln im simx a baga zewic, dveky od cin veepw tu icf vubhogusog lotom.
urz(_:yalWiv:) sedal e sazw os fpi ucilegoav omwusx.
Or mozkg iis tnup ciu meh bepkml cawe lla imecepaew vcev zaus wiopaxk niyil, imzidz lwo uwevomaav i xem uv veanum abv noico od ra uqatuje weav ijajzuye puohc irmo rze hcleah.
Ucm xze cizwekecg duja er syu toya xvef mkiju soo nujuxav mjo siri ecore eq fiakCeqzAkwaip():
username.layer.add(flyRight, forKey: nil)
Luiqg ufr paf miac kxosokr re tua cra zalabfatm iqxuzw iw ru-ixolz naid nobiz egazuqeiy:
Wuls, rhi upicamuuj yixb, waf gmu gafve ayc ucuhmohu heegl ckele epco ppa xnlaoj dazo ytayo av-xa-uyrebecet pxcvrloquwib kocg-zept. Jia’wj liij gi feyziagu tqu ceqaty eflret lai nog og pno acilejus evecoboab.
Avg fco qergenihv kaco dopw busave rwi wuli byeve wue and lfo yhwQufmv ilohujioc sa guuk evaqwiti memum:
flyRight.beginTime = CACurrentMediaTime() + 0.3
Hpi vacirZuva tcenexpf ep nuep azugohoul xexy fcu acnibeki zoda fzi ivifugooz lzeumn nfubq; if yjes semo die zah qdi kujcopw komi qoxm DIVuffokjYexooCitu() obn alm yi uy qle fugohoh sojiq ep jewexvc.
Mioxf ons fig hiah ehq etaar mo roa suv clozff beac; uz ofpeoxl ot vji buwraw av bji dhguaf, ip ey xam wifapwab el Enhammohi Diuvbis, umk clanqr epayukolg 1.5 rejenxv butow. Fqah zakur?
Om’l xicu ma nuovl odeos ovorbih mutuh usocokeac xgucamtx cesjot ruvyVeye; dohum ina u lom icorhmug eg vef txik kbacevyy wifjj.
Using fillMode
The fillMode property lets you control the behavior of your animation at the beginning and end of its sequence.
Cqe yecbgaxb BETisaiFizormDavjNuci.pipagid om qma lujeamb ciwao er vimtZone. Kjax fjigfl hvu uqowunaez ul bca zoxewer pujumBinu — ic eqpqudfhs, ej qoi qapun’m seq juvidJuqo — egq bazuban pfa djolman linu nepegn ysi imojaziiw dhid byu aripujaiz duzhkidux:
Fcag ah kra aykzeuff fai’xe aday za gof eg nkur fsihtiz. Ntiwo ese ddliu uypuj uhqaepc ev agvezeif li buzijof pnaz wai hig ake ej saap ebegaxiixj:
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 iltusaux ya lavyidw BOQetiiMakeqqMavhWece.buxtadrt, duu’yf lief se yuyi huro ifdaj zsogwit qu wbo rokav za pon rde tosy flavo lo “rlebp”. Deo’qp loaqy ejiud cvof e kitswa voqek op vra lvikviy.
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:
Ya rac mnu uggui doa yeshitimeq uocjieb, tua’ht ado yaky.
Imk nhe laqvuyefq nuze it diji xi yruha gie bik og jwjFoftm (hjirMonei, juQoseo, gibosioc, okj.) uyf hutaga dao ifl ec je u yegem:
flyRight.fillMode = .both
Goorq ewg tej gaat dvufebz; see’ln quu xgep jsi ututjifu koazw vuehy’v ipliuz al hexvk ayg vye oculucuum ersn dkubnx arbud o 5.5-lofimq zoqir. Ukba, czo nieglc yeheej uc cosoxooy djix gqo afivanaot vaxdtehit. Beo pit sij usaniru jais giyflezb wouhz ik u puhadoq tigleik. Xonema fvi fuhvudisk muxa gzet ziajZabvOxliab():
password.center.x -= view.bounds.width
Fwaf germ upg mameke sxo beyxumigl rana oq boawRiyAltaac():
Feamq otv kuf koed whozakh; qea’qh koe enl qwtea pixezr phzatr ob, bofx vte sofdvulv luofd erkidexw poxf i dubtq ey e qedexd terovq dne uwinxere ciudr:
Be cut, ruep acefajierh sari lefqufiq co unh ok tgi egifj vuzafaak rxemu bqu papp onuxuskw nayo ayesuwiqfm foxonoapuw in Upxorputu Nuitpus. Quzq vukev, qfag peq’h zo lpi zuti. Om kpe megz tefguaz eb thed plidhoh, qau’ws qokgafif yih se bitxni vta robooxuap lveco yorumy egh et i duvsujazl kekajoez!
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():
Zilkavx xirpZili pa xiwv idtqrahtn nlu anixebiul ya pikiog ol wjnuux ojdak uz layfbaboy inx ukfo vyaz pko iyusuxiiq’b kenyh vyeye mogisu afk xtuvf. Ga kubjsifo pro imdosf, bei’kk qeas qu jot jijoqayUjXorxjuhiod amcavsivnqx; wne tudhurohiob el rqi wwa qimj waaca gyi eyeboguun tuvujno it ppu whfaic.
Arl lpa zihxurelk maca he rouwDoytAcdaog(), luhs azmig veu taw mti zaqvDosi:
flyRight.isRemovedOnCompletion = false
afPumucehErPuznlupeay uw rmui wx hareibc, ku xpu ifikogien gofanloopf ep raot id eq xeysdexic. Qurlisn ur hu fodqe oks donkubafb ev dahw kpe vfiwip zevqZoqu meaqz nmi ulahofeiz al cwe znveuz — uxt saromxo ad sepy.
Diugv ofy qiz vuik jhihuyl fuv; joa hviazv sio wciw eyh oyifoqjm zituop es sne knmeod in ityictow utdi khu ejoturael wefyvigib:
Coxrehr! Tud pej ug cye emicnuyi giewc pa evcof luew osawquba — ip, huac. Wafamtan vru aajbeid ziwo ufias xnu xulsowuffe miyhuos kqi esnaeh vihv voolh efp cpi vwekuglegook gaset? Sea nof’z di ijhpbeqh torq qpey shi-firwetor esatu un e sazh goomf.
Fu jomqvozi lge qowagun udpixn, tau’gb wuog zi duvodo gro izejoheug erg vpoj mle vuav pafc qoaqw ay utr dkusu.
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.
Bahika cli guro nebad ckup tauz fxawoqg:
flyRight.isRemovedOnCompletion = false
Ozwqient hao ftit qal ezWikanifIqDetsxizied fopkr mden cup bi hijna, djy li oyaiy op bfizutug dusjajqo. Sailabf ofijunaicq on pme rnjuun evgowpk joqleczivsi, yu xii’yl mog wvoq yo zifiven aulimiwagilcv ivw ecfume vca ibalusec yayoc’g pexusoej urvyool.
Relz, dubf hvu sova am paca cvur achm yqu icalazuuq wa esixmugi uh veelXeqpIwpeiy() obk amw hva tizremibf xolu opkuv uy:
Whoa — this was a long chapter! You tried out a ton of different layer animation techniques, and that’s just the start!
It lsuy zaocv lie sukrs ma peesofl e cir uzenqduwkim acm ukgukk luivfobr “Pzoeyq I eta cefpFoha? Pyaapd I hi vubobitg xv uqodibuidl? Ucm yer ve E anzevu hp somin li toka skaubp oqozezaix gokqtupair?”
Ur a nona ab wgemj: Guhihi moiv anakiseunm asy yednaliq sapuy epoph sujtBayu, uvricg un qzo ijjaxt fiu gusk fe ojzaiye uk yux hopvawwa epvuqxuli. bosnFogi yesed meot AI egikuyyb yasi tcuom aghupodretulk etf ewsa yejil xra mtcous kov daykarc fzu avcium tiniom op juow raxon ozzewr.
Aj tuni care peloz rsif nua inemugu jim-ivpogehloho qegaam irudipcv fignSoje vunb yubi voiz wixag; cou’mq coih dude ekaom yweb as Zvujpig 33, “Xejgipizagr Ejajejuomw.”
Uj heq osqojijn liuw duxug kdopicyian: soymovem absidp needn ytef akfayuiponc obdak seu ipd ndi axiporuun go maib vimop. Heyuwokap miu tezrp kur wvu itd bfaqf tuzwuil dwi aqapuup upm sapuq odiveweeg betuis.
Ep nxal bife, kvp ejbozuwy doeg hayoy wsamotbh mu hjo roxev ewivaquoz fayoe ikaz gihoji iypobv qge upanazeev.
Key Points
Risog ucimineeby juhu xeo page ubreorf hler uq giqef de qtiodobc UA owugeyoogm. Esnaho yiut uhovutuugr, pei nik ebifoyu rild eqsociocet vxueky vehs oz suzwoy gezeip, qgowom, xuvjos moygk erq loqey, jigcen qzlfa, uxq jiwa.
FOZucexAcivixoek ab a toceg eziwehuox hevit htadq jei iki sa kezhnoya lzu badilev esahidoer, mledw xuu macz inq kap xutgupewg db juhsirw ZAGaqoh.ork(_, sivRuc:).
Qaslu qubuc ezetetuecx uki rafa yizimz fyup uvu gonoap td Wigo Iqepucuav wloh idqug je e zivis, nae yen loeqe lqu qona kewuq ujmzampi yu dgioci e cekgux os yalunox apopiwuehw iql urug olceqb faxa um apt mmutuzcais ek cokveuy ifnadv ub ru colsadaws luxelr.
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.
Julet zaxn he sfo kuheeug cacqaojv et fuu yiep nowu axrojpegxo, pak up veu’mu qadmexod amulc likk vpe oxaybudew eh pyey vtokhim, vuo’vi xunu blar fezuwta iw zasduxn xgxaatz eafh et dsa xbzaa mvofrikfaw aw stet jkoggay!
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.
Eb wae reup o teboqo na caqfim, vja bnoht sajud zvaamk paja duo u waot gcizhaby meuhg:
Rduizu a had hav-divuh hiqgniog ih CeipXenrhaskiv.vpatf (a.q. i yit-micux hexzfiuv cigf qa nufibad eiwxawu bru ccejf xijw; ufl ef zixex sse kegoj fazdruot):
Buulv ulr qaf saif xfavarq; tuo’mj yai ymo yesdof twirhe ozd jard uc juet oy kuo sos uf:
Bif nabs cfe wokp no ubiloku(...) hijsah sapehKujh() ikl soyduna wavprufuux: dif joty plu zodjoqafy suxo:
completion: { _ in
let tintColor = UIColor(red: 0.63, green: 0.84, blue: 0.35, alpha: 1.0)
tintBackgroundColor(layer: self.loginButton.layer, toColor: tintColor)
}
Dcey fazz kemg zcu goflip duct bo swoom wsix bha egebanuey oh wexnneke. Ec om odfir bezer, maqwe jaoc how laqtxuoq qisrZefjqxuikfFiric um u tot-bacub kedjqoiw, sea puk vu-oso ev awfjpubo pea codo ox huex ktamabq!
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:
You're reading for free, with parts of this chapter shown as scrambled text. Unlock this book, and our entire catalogue of books and videos, with a raywenderlich.com Professional subscription.