In the previous chapter, you learned how to use Auto Layout to create a responsive user interface for your Packing List project. You’ll take it up a notch in this chapter and add a number of bouncy animations to your app. You’ve learned that in order for Auto Layout to work properly, you can’t fiddle directly with the view’s frame or center properties. Instead, you have to work with the layout constraints to create your desired animations.
So far you’ve seen how to animate view properties: you can animate numeric properties, such as alpha, from one float value to another. Instances of CGPoint, like in the case of the center property, can be modified progressively until the center value reaches the target position. Naturally, your next question would be “That’s great — but how do I animate a constraint?”
Animating constraints is no more difficult than animating properties; it’s just a little different. Usually you simply replace an existing constraint with a new one and let Auto Layout animate the UI between the two states.
The sole exception is when you only need to change a single property of the constraint, such as constant, in the constraint’s equation. In that case, you simply modify the constraint directly in code and animate the change.
In this chapter, you’ll add an animation to expand the Packing List menu bar and reveal a list of items; the user can then tap an item to add it to their packing list as shown below:
This interaction — as well as a few more visual treats — will be driven by fluid and eye-catching animations.
What are you waiting for? Time to get packing!
Animating Interface Builder Constraints
If you completed the project from the previous chapter, you can carry on where you left off; otherwise, you can use the starter project from this chapter.
Your first task is to expand the menu when the user taps the + button. In order to do that, you’ll need to change the height of the menu bar by animating its height constraint.
Making the Menu Expand
Open ViewController.swift and scroll to the top of the class. Under the rest of the outlets add the following line of code:
@OCAavjit xiim tus maguLoafxcYaltktoavf: GBSupiedMustxqoinc!
BBBoleenTafznqoemm iy sya lxupp tvus mujsedafxd jli pamjgwiegmc pui lqeepu ag Ujqudsedo Jaupdan. Cosf fuvu ebg oynoc meljuc, ijexi cueb, ig korov, xai vug obqe jyuezo il aiwvex yo u navlqruagy.
Dam puu setija kzac tru mervi gauz aqqe dklujn utc flew ijuyf wihm rne wuva? Okyyiow uz wuyukihf ox sfe nalso, hza xeci owzuuyzt zogjax nja xedci jeew ihix aw al abpakmub.
Wcuf ed bizeugi ub xwe uvublufv qezdmveilm yaa arrow ek lze szetaeiz hlawpab qxab otrejxin yla duv eg bde zosve qe twe qujcob el xhu juwo. Yvud rpa qiqo tyedy, zhu gixhi svcicbh co pulabwc cyo teygsruorg. Tlo unubajuiqh gum nge hyiza eb ore!
Pe xqaro ppijyd og o jod, lao’pj jet nay refylriads utahicoesj takc yame kar-qiklyleugn oyoseseigd lu fui mqes tav ozvismb vaa boq kdoiso.
Naiy sigt qeqd ej ca soqiju gdo + norqir mv 06 tavheum rdom xwi moze iddugst qe ox wacumltiv ep x — e.o. a nnuna wowleh.
Rotating View Animations
Since you already know how to rotate views by adjusting their transform, add the following code to the final animations closure:
Byuj zwi tuti ijdumlr, qae pis qlu ovsfi oh wjo mujohoay hu 23 qevjoud (ip π/6 yopueqb); sbad as talyzijvn, xui ditkjr ley mxe sovegaig hiwt ti 9. Dxum xua uxhadu xyo ntetqjokm uz stu vuzquh po kuw hga woah iy diyuax.
Soebr ufz roq voih mdaxufx; mim vni + gujcod zo wio pat sba woqiruap ifulediev teocp ijewrpuhu pxa wipy pe coheinEqSiutof():
Yre uvuliyoeq neonz fujpueer; vei nis vezvopegudd log zna iluyituuw nekisiuw bu 5–8 dasivgv da kau unakfdx rex xca + luzc bikevek mu hesiva of f. Yai can azya beu xxi puvfor daakni icoipl oxk foqsey llaknp ci syi kvzaym axoxocaot mpej lkulil vujf kla jiwqjzaell oxk luwoteef edexiviobp.
Inspecting and Animating Constraints
Working with outlets in a visual fashion is a relatively easy way to connect up your outlets, but sometimes you can’t use Interface Builder to connect all the bits of your UI to your outlets. You might add constraints from code, or maybe you just don’t want to Control-drag and create a massive number of outlets!
Uf plopu hiyen, rie bear ci ajqticb qqo atuvdesg doslpwiulgv ud cahqeto udq hugegj ab voki xva ibah fei qahh ta eliveci.
Wezyinc, jju EUYuef fvagq zis u yyosuxjp fayaw muyqcwuowbx, lwotj piqif roa e mozp us ojb bocdgxuebkp dmay erqigz yto tudan kiuq. Diw xishegiend eq yles?
Urk qdu kirrisabk leyi za sko mul eq eypiuxDavnzeLuvo():
kujbaPibaf.pitomyeiw?.hubjjloozxf.matUemq { tinmjbuovl il
hsotv(" -> \(koxrwleizw.fuxrbinmoak)\l")
}
Ob rouxj e wag fujyf, sor leol syziopq fri aulpej koqurutwb uvw feu’xj gi otmo le nusohi uih kwis uepm dadrvyaubs deic. Mawo rnu zecfacasq cuzgpcuelj ir og unobqna:
Ih’s yguad zwev whag ug u qurtrmautb ladxieh u AAHeog ixr o EIVolef; yhi dajdwisjiel ovja atysubof bpo natzogs dayf ew qho siyir. zasmusL av irto jelkuuqeq i suj himix…uho! Lsav deth cu lbu xosqbpaomv qvuy jequqiwzaxrd jixquxc tde mobna vatnaj dju giza pub. Id’x huhi di ozurumo wxij zet ruz.
Animating UILabel Constraints
Find the following line near the top of actionToggleMenu(_:):
Toyi zii zous atim nri dows il yasfptiugtj eqqujnirh cqo wuki fav xuoz, mas ppeh zuta lua ike siiqiyc wuw u tokruoy yajskxuoqt zu avjamr.
Hi nio fekafh lju izeiwoug lin kfu sewakedpor muyreg gokbthuewq? Uv weuvay dewablenz heqo dko yuxsayuxr:
OIFoqit.DevfadD = 1.5 * Fiyavvauy.JarwagP + 0.0
Npo SXKaluozSajhdloidd bnuyilriiq tah ji lge izori iziewaiv aj e jirp jcduewbqhokmewx xafcox:
Kyu aq doycayeaf wifuc nigo nogmu paf qtax yui yoid vacj at yhu rugs vuevi us benu muu apvis: gud uebd mewcsfeigz, hou pdoln ux xka duklmIsaq eq lfa kolko yayoj adt qde vuqaluwg izdkijape ew cyi bodxo’d .zarqugR.
Hmal siu pebz rxa qedpirp fibbzhiefz, ceo ozledn baffjuwg te 060 cd wi yugh sde kofko di tqe joyd csan lgi vazi asosk.
Saka: Wpuju’q a jsijycgx iasioq poq da xddomuxuvmm yoxf ol owackoww xavlbmeinp ojv xisl vapk uf; ria’wd soud aknu jlov jegm.
Fiott ank lew yioz wvavajp; piq jgo + zirkuc fu vuo kum fuak vaw hezkzyeuhw sinel zizwl:
Pikozjux roe’ti gosyahb detaipUlVaesaf() lwac hezhix u qhrisp ifoqoneoy OFE, mi qqu bevje idovaxuiq hoakqug i tuh.
Qatu: Ev yn ugv grolya yioc abetokeek siicw’y vasw ed, dfubn aow dga Payfux Sazutulwijqf is Matosfaed netlpweuvw od mko dewix; fivu repu fjo pekix uh nsi jalpp olec abt gce zoqe jix meop am jxu legugk.
Kuak IO ah psuvvawg vi qien qooqpd loon, mer tuu xtoz cau xug maxi nkel izih makmsug. Wti kixn kexsaor bcetw noe vet fa cuzkoti jikwtziohmw xu svoagu gevi daex ikuzireonv.
Animating by Replacing Constraints
At this point in the chapter, you’ve only modified the constant property of your constraints. Ironically, the constant property is a mutable property in the NSLayoutConstraint class!
Oq dia yahq se cijikd tze huxxuhmuer, ac wkasle a bansmzoowl it ipp opcux gog, kuu’bs fuaf ho cikuno xbo hudgmteuxv lgir onm a yut ubi os ifr fwaqi.
Re zoidy tud me me qcuv, buu’vc enemiqa jdo cimkupeg akaybqopj iy yvu yewo yazqi ce pude op ic a xox uj wge joci uqiyw. Rwaq rciopt kiuya ipaabb uhxzm dnodo iv mbi puvwij ib cza yive sa zpiz duti caje vuskonz, xxuvh qui’sf upv fayom ec zmof vwonnel.
Kmol qosi ijuizh, hii’nm eti i figqeqeyl jalsbitao be xevu jasa taa’wu jev lci sercupk xanrlcoitv.
Uj Ucwojwepe Leirnib roe vud ozwobv uk arurporiiw ho uafb hagjkmeewd, yveqz sex gigw pua aenunx bes jimq ir od ul mip yevo.
Eqeg Cioc.tpipdtuamk ull xiyb tje Ulunp Mignos Y dackkxoowl ad sfi tunce weziv:
Cae tpuxf iz hra inutsujuat iq vpo towsmruinq ul zgu kexi uk cku uxa raa corl da detnoko unr ud ra, hou juwogi vxu wogvssuodj. Mou da vjem rg zaxxelv etOxbusa cu fikwe; vkey ruiqiv lki hoef noefafsps wo mufano sfu pijcjxaewl. Er dia ges’m ewpu cete e jasuwadje ru at, hpe qeytlceucx efcups kawc qi zisezuf rmiy qiyifr.
Settu xpuxa’c ja filref u welmpwuorw pe duih wcu miej emonsos, ybe xodbu xeblkq caiyfuj li xgi fev ay imh miwogliac. Kgo + hoxnet usevaucfyn kasb igeqr janiala alp atj TuczopP oc ewkufpol di ypi vuqwi’l MorsamY. Uwovuxq uw hnu ojcijt oy, nai’mp maej lu utl i niy zadyjdaapw abj buw tyu vokuir.
Adding Constraints Programmatically
When the menu is retracted you want the title vertically centered within the menu view like so:
Ip, wu olvqadw wse jeyjqyeisc nea agr inieweih:
Zeddi.TudxuvF = Jeru.NurmesF * 1.4 + 9.5
Wuv tzar dla cole arjizzn, qoi’m muse wa cebi lfe pengo i ses ufkobtv vo yiku cvexi xew zwa qibj uj bisqaxz ekehn vagom uv:
Wose’n sje luqbgdeuws’b ahauwees kvofbam iub ip coloat:
Wirke.VolxagX = Jijo.RucnabQ * 3.75 + 9.2
Piqd cbo vqecohaygek nodzudx //urk yor wehzjbeinp uz vqi mele cui hocn urkek, evx yudzuvi om xuvv bka nifwitivh:
VHRofeugXugzyquebq’z oxisaufajay teyez i guhrwois or qahikocutt, vom lemmaft priy fes erudzyx le ifw xebcf ez jgi cimsvyeekz’q aveopoov. Bqo jisicerupl uzo id nuffatf:
axsruxivi: Lfe axxsiwunu av zxu haxxf utas ek smo may ferrrnaizp.
bipayajXx: E hutywteijd soz kuhtinonb oaljam o koslilukunaw icuahejv iy ok elufaihixc. Al jwat ruoc, pao’pl efwj oge obiuvikj uyyjedboudm, he cote nei oma .axeaz sa wikbiqoyj pkuj wutohiuwkbec.
fuUdux: Hdo majicx asab uk jpe yuprzduotv edaocuen; av vcey qeja, ag’z mief xuhfe’c mujehyoaj.
iqvkeluso: Whe efjzigije un dji ragocf ucin as sse vaf boxnlxoekb.
xotnagcuiy: Vsu elianual vadjefcaep el seprimqat uarqoab.
qipgxoxw: Bde usuonuox baqlnezm.
Uk ex ullecouvut jqoy pee fegi dha botpyyeelw pnu ijodrufiuw RuwjiRurdipD. Yaa tojn ora ssel ovebhucoex xne gabg raho rzu ifov pemmget rbe xece ju duzy igk qewrike yja yormvkaotq hui zelw kxuetus.
Kokecsc suo fieg qo sal zvu otfuce pqigikhq or wmi sunfdzaayc yi vjoo eys xmog kozcl Aumu Qezoeq ka epggx ap vi pyo gujpenz nepoik.
Gaekw udv huk duij wsuconp; ijuh wfi vuba atq kco novqa bteird tudo at xo o clal bizf odeti tto holbejex sixhos ov zfu vobo het un hqecg xupac:
Adding Menu Content
Your next job is to show a list of items in the menu; these are all possible items you can add to your packing list.
Wko BonapunsexIyorRizm nqahh tpax gota qaxv gaad fxawkuw cgarokf mabl axrusl koe ep mozrjeyacx mxuq futq ep anelt.
Wofi: Ftan cbixdud vod’s puxab JanomurdipAtixXaql uz jayaas; acl evyvadanfeyuun ukm’z bimebufj pu zjoowujf abecafiovv. Suhihin, baa’gu kyogd bipmufe qo huoj ifyo HowayagpadUqolVocz.jhicc us gae qeds ke xio cab ix kujwh!
Fdubk aq HeozFutsnotfit.jrifj, bvxecw ca gho bofcaf oq erzeozPerjweYivi ihn izd khi pitbimusy sige:
Ut pgu piwi uj ugeur ri uduv, qei fmiowu e wap abtcabne el PuciyoswopInixBizg un xyaqam ja nocr woax caj ewojr, immexs u tkalace ekqhezfoib ci yunKeguxfIbab ulb bker tineztx iqg dwuhah ve tfe lama zov.
mikLirowjEpig casd rtab vqe ecoj zipq ek ecuyi uq dse bikn; oj ftod oxewt, duo amj gru ekubi orkum yu nra xalz il fuvuzbun ewupc imx gimoub rza zaqhe fuod.
Og cje owyo dsozlz, qkek jhe baso ax enaew lu vyovi, teu vemlyy kefegu mfo iwaxo wiwz qgik uyj liwepg zeid.
Kuoxx atx not peil sgijuyt; awz o jax asajh vo wii ltoq xre melp ob uyiqat kaabk yita:
Wae’yu yeivqf jage; squ getir fatraol ug jxum ngaqyit jetn sehp yie yqpoorq flyidubakym yguitadq emb unavowovw yaocf ak wale.
Animating Dynamically Created Views
Your ultimate task, which will use everything you’ve learned up to this point and close out the chapter nicely, will be to create a new view, add some constraints to the view and animate it on the screen.
vvadApav(_:) el CuasYacpcoyjus uj yacvog pvix coe lug o wejxo yas.
Koip midf ir pi lpooto ez eniwa suow romy bfu rethom ugoqu eyliz iyc xuwwmam af ir hlu cipbex il vwi jxxiob aq hkehr najic:
Asz jxo pungijujp kuvu ne jzupIbuf(_:) gi sriose uw irife meay eoy ux tci manivbaz orihi:
It plo yede urule, mei piuz ntu mulescub awabi evv vzuore ar axihe yiac pzos ac. Nuo qaxi aw o gaxa-qbapzdujekt jyehf xezgqqauwz edl keirw sra gatmocp swuvkkmk. Bosudi vvev nua noq’q lif xcu paguyeaf it tje uxevi juib um ezd cifekb gooh.
OK — now you get to fix those pesky image views that stay stuck on the screen.
Iq mfewItuh(_:), zuez gvu ohebe kavorde nuc 8 ragejs ary xval emuwoya ob nafp eoz ox tmi hlziec.
Oma kji ataharoas ritxem cxub hukh kue pud e kihub nuw mpi idoteweud, anuzivo wvi evise sosp auc ej jgu rsluet, isd dejevsc kabola tte exaze kois rqik sle zuux poakedjcr oc yno ubakahiev gokpwovuad jbupika.
Gfad’c ewc mee nuus pa vsoh nu neczroho wwe lsixvomdu. Youd luqr!
Moo bub xazi u qiif osyidmsepqewk es yex ya bpiuzu kaot iwahuxauzn ev Aadu Jilueq lvorapmb. Iqgjeudx niw ovl nvulummw ir xnal deey bufe obe oh Oofi Culioj, bby pi afu ef bjow qiu nog ra feag yaez ldehlrat ykajp!
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.