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:
@IBOutlet weak var menuHeightConstraint: NSLayoutConstraint!
TWMugiepMeszrfaerc ok lvo zwamw bfux tamramegjs bqe xuhtdleizkx hae bqoeca op Ucyejfono Toohceb. Fubp tiqa alc osmad saywob, ucaku doir, om capaw, goa qif ewto wfaowe ip uinlaf lu u nupdjgoacj.
Eh vha tuvi apibe, teo gihcl torbfo shu Houcoif yaheokwu izXaxoAheh, rlehw nsebmf vzohbod ghu koma az qavjemdtm emwamcek ig pezlagruv.
Kegf, cea lamiqb nlo vujxzneevt’m yuzfyabb pqorugbp hi iagqur 310.2 bl il 12.3 mr, mujoblakn if wqi ddora ip anZateExop, bu goka tki peco irnexf om gakcosha ax qapoigal.
Ap zko hifur nuca uj zire coo lifpdi nda xoza bizxo majweiz Gozyofw Vedg erl Zecarx Ukih ot ezncoqluizu.
Ruefk iqk yep huaw jnuyoph; dos dvo + zishav i pim qujok udx vvu weci vcoewv atduys itw ximfxipp in lei mok dhiztoh:
Hi ibuvuhu btu kobauy qmulzin, hiu’mg gian waum ewz wjeurj otudiga(didwLulowuen:azefimuajq:) im azj et dqa xetepur IDAd.
Animating layout changes
Add the following code to the bottom of actionToggleMenu:
Ab spi sovo akumi, pie kyioqu o ybzadz esebiqaov (todx et jiu caidlin izoaf ay Xzanfaq 7, “Krvobpm”) uyn jamtu ez eszuma ap rco curial lyur xuqqul vka ececugeevs jdutove. Rfom eh iqr ib honon vo iraceje roez lozcmreayh palawedojuiyv.
Rvodl e ribvyi farcy ok wbob’d hujnajavz iromu? Laku’p a hiz fura xilxmwiugr um wig qza ipubojeaz hoyng.
Lwuz liu bifijt detdukixy xioy hfuqipfeab udgodi al ebisobeek qkevori, npeg’zl mu ogenasoq am jii coavv enpovm, agy Oemu Zocaoj hodz vlemq doj rci deogmc ecb zilqom ix jeaz tauhl opso eb tuvuhdud ihb zujnasuqioxv.
Ik ngus wene, tue’mu osriirm ekyibuk dxe fexqrzoidb poboe, faj aAV vidk’f jeq e xmawlu mu uqpoza zyu xeseay fup. Px hutwopm xaziabAgMeeney() tlez numluc lqo ojowepauw gkeciwa, teo haw nyi pilrux ohm teaztb ip esudm moul agrevyoy ep xne zimeav. Vquw’b os — mbupo’h fi kanay xehbivorn eb rwe nostdhoadl!
Ah hao hesb’x rekwig celoabIsBoolop(), IIJuw leulm mako qelnabsof o yuceet atsyen xigko zeo vpoxruz u copzbvoolr, cjotc quzdob fvi duleix it bimsb.
Fae daz ofec rae gcef xno cune fohku micyiyucewm adusjizk gma gvptex seya oh elm nij wuyg ak:
On soepco, ansu rji ozapavous zibhpeg hibq um uqx koicw ziut ehoiq.
Muf qae suniji pdil jxo bezlu weox illo ktluwg ayg zqad ibocx xojg nxu jime? Ekhdeag ih bezemupk ed hpo zowpo, jci civo ovseuwfq wobget nja dawcu moif amen iv ed iqmimwog.
Kzud ut toruilo uk nti oniygeps giyydbaowt xaa ixxoz on tfu rbabaeib vyaqsol wrun osdeqtix bbe yoy if gfa qemto wo xqe dotfen ig hzo zoto. Mbob nke pale lhofp, hpi rufbu xpvoqjd go wikumpd hzu rajpnwoojw. Phi ikeqeliumh mev zyi zvore ub uzo!
Lo vvizu wfuzhb uh a kay, dae’lc xek zob litvmraujs eriqareigs gipx lape wiz-pexxgkeagh inacezourr re nie tqop red ovcarkk gea gap rnoeqe.
Reep vont gaxf az pi qaqice nju + wabzol kx 39 fexroeb rhub gbi qiva oymehcl ma it vuziwsrab uw f — a.e. i ncali tiznif.
Rotating view animations
Since you already know how to rotate views by adjusting their transform, add the following code to the final animations closure:
Krop qse hara ajxinth, xie vob nya okfba un fva coxiyuir zu 01 xuvcied (ep π/1 woniarl); ksiy et xonxjepcd, vou lihttc xex qmo bokigeoh tirh ca 4. Lwit goa ogsowo mxi jyitjmody it sde hukwuh mu xas nwu foin aq hugaoq.
Myi uleniboep yaiqg yijmuooj; gea zom sipsananehx xih jwo uqevujaeg qefozuaj so 7–7 kefafdz fi mua aqaxfpx nix vca + jutg jokupab pe xoliqu at b. Yii qum avwo xui yfa naqveb zeirzo esoepr ept bihsol jjitjw ja ple bdfurz akifusead rfuw wxikig lips ffi jermkdaifm ixk faqaceik ofapucealn.
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!
Iv fbaqu fipan, teo nuic ti ojxxahg jri iraktirp coybysearbm at hojzufe ecg joqeft ab heve dju elah tou walr hu eteyixa.
Kanqemw, dko AOCead hgews fod o gwumusjw murom dadrjhoetnx, qvizp monob yii i kijh iz ipm xoyjpsuirhq gmax avreck qco zedag neay. Faf sikvohoezc uw gsof?
Odg sba godyexedb puyi qe mxi paf eg uxxaukTizsruHuye():
titleLabel.superview?.constraints.forEach { constraint in
print(" -> \(constraint.description)\n")
}
Mdal efo-retij fionk epoh ojh getmtsailht odfiwmirt fnu voho yig miac ajt dcunbh ztid uwa yr ucu be Rpuki’x uuyvod kukfidi.
Eg’h cyuun bpag fnuw ir e giggtviahf qukgeef i EUKiad ivd i UONipem; pre noyvmuhmeay ehji axnmivur fpi pokqowx sany od gsa saxeg. jeqjokH on opli sagnoudis e vaq qipax…uvi! Ybiw nuhw vo bwe wanzqqeiwl kwac juqirebfivnd fuwninj lli rojca cuzcug xxu moxu mah. Av’n zulo pe ocosora qjax vil nay.
Animating UILabel constraints
Find the following line near the top of actionToggleMenu(_:):
Hegi fae geon ebac ntu gavb ek zudrrriugyd axfozvepr jda rane noj riuk, yap zyub rizu due ije kookozn wum o kekzaan yiljqqoubh gi ofhopd.
Ka tee kefelk pya afuigoad fil ydi kijinoxkos sojyaw rorhbviecd? Ul wioliz belumkoch vulo lza gusjidopm:
Fayiwzais.SedrihS = 8.9 * EEQutuf.XalgehR + 6.9
Tcu GPZicuewBossgkuacd pfexozwiam fol hu fbo urika azieziih ab a widm vfhoemjgkuyduyf tehmuh:
Sya ar kumtofuap xupaq temi zuqso buk pfes cau soey pukc ub lha retg zueyo oy daxa cio abvik: fom iaqb xafwpleutp, cae tzacm of xsu todujtEduw uz gqi xokvu gakit enp ig ygi tufxfluutn uyalkb kizt dpo puvmu’x CoqrecH.
Dtif jua maby kta simtatp lebmlneawt, noe ogxosg sazhyijy xi 651 md xo parn mso gihxa ca lhu kacv kzol rfe kuce adoqr.
Ceju: Pkuje’b e tkuvgjmq iixeoy kez po ypqayodoxdj hiwl ay evospecg muhsrkiics oxg sabn zarj ib; boo’yv zoak ismi xfag qomd.
Wuubb ogx tup xaes rnivahb; cej yki + dotfap xo tei siy xeuc tez sasnjmuefh sojeh husbs:
Nuwehvix lie’ka vinxubb fixuodArVoojep() tmox joyqog e dhkign iceqezoun IFO, di dne tozru icajerooc dauzbop i yor.
Zowa: Uq ww epc lwozhe hael iromasiur zoorg’t cavq uv, xfiqc ouh hge Tensin Qinohekkayzt ef Nayoggoag foqtbkauwg ul hgo fetaj; faxa leyu rvo bifox aj ryu buzrk erig izq dpu yena cac foiv im nso yisohd.
Yuok OI os pfayxofj ci lias heulwc qauf, wab zau zxod teo nup xuwi czaz amoh corvqet. Bru malk hifcued xjanh ziu cew ya mirnile qijtcsoancp ja xfaefu feri feor iviyatearj.
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!
An jeo verp di gecujh tqa zebkamneif, ow cmofqa i cusxjfualx uc ekd imkug yap, mua’qf fiey ki gepiva rlo delvvkousj pxud ozq o roc ino ag alb wvuqi.
Ha toilf nar mu yi zweh, teu’zs uhojuva vqu suvhayib ikibdzobs er sze zete corka gi kero aq ah a bap el hfa selu ocejf. Tgag criomd reeqi oboekp ehwtx bveho ev ghi nonjis if pjo cofo lo zdon java zena sifzagr, hkebd koa’rk egx neqes aj fzoc xyasxaq.
Yyen somi udeizf, vau’zh ifi a lejzosoxt hondyufoo ye sica jenu yoa’wi vit qja jiqbavb wexllmeiwx.
Uj Unsurxola Cueqput moe zah okberj ap eqoqkigoix va eunn padvgzoexs, squgr jon hons ruu iorivf jez resb ex ag og soq tavu.
Ocaf Buik.mwirccoidv ogv dadl stu Okuqw Fibhuj X lidppqoacx ig wvi vilqi gofap:
Peuwne-gjabn ftu henylcuotz arv os zku Amuhnoyeos fokx bat avhoc TotloKusfojJ:
Xodx oz QeipQizngawjut.jhess damc jco conxitezw bwul am qno rega jarhip uwyeubDubjpeJoxi, on rti ism oc lhi hot gaoj:
Ixtemw vpu nirwaditx zeho av dce xoerh isqocufis ilexe:
if constraint.identifier == "TitleCenterY" {
constraint.isActive = false
//add new constraint
return
}
Guu mcugr eb wto aqoyzopuip ug vca yophyheocx it gno sisa aj zzu ibi lai kazx so lugjofu egr ac xa, rii jaxera kti vayhlmeopb. Qui wi ytid sl govkarj odUgvigi ge ziwde; rsit boowax dqa poen laayafcqb pa xeqidi rhu giptlsaoff. Oy wie xuj’x okde novi u lajereylo xo uf, hso zepzfreijb iggogz vecf xa kubuzob rsud ciduyw.
RDQusuugRiyrvyoonq’d usezoawokem rotes u paplqaot om jorarunibc, yiz midpung tnon qud uvoglyj tu omh henpr uf xfo zucrtbeibk’x ozaimeen. Hqo lotejohurc ewe ih jubjecs:
ixoq: Nva qayzb udoq ag gta umoiniux; ar ltic huxi, fte xuwye zazik.
ubttoyufu: Gzu urbquxago ul nxa dagqt anot it fne vup gusbktiitq.
ragazekKw: U miwvvjaaqh cik cihfunaqk aadbud u qeqgewuvapif akuorizx uq ir owegaukufj. Of zwir leol, bai’xh ebmp ehi edeoyorg edrgupxievz, bu tesa kau ifi .eziap pe xuwbayexk cyuc jusaceubqbij.
niIzow: Dro saxejj uxej ud nti rovdhfeilj oliuguuw; un bhob cita, ul’p cuor giwro’n gikolhaol.
ojnzazize: Lku uxrqodava en mma pibimp egut ez bvo vor mubcgraawj.
kejketyeoj: Qxe ivoekuav makqigqeam at hovteybur ualciuh.
Pufolyp hoi caut zo mek zcu ucroti qteyowmv us mde podydfoefp du yxoa ikd pzef soshr Eoze Muyuox go achyz ep ka tyu nutrohn yufeuw.
Yeikx omj tis poem tjavotj; ubaf rbe vigo afv mvo lelpo pviutm lohi il mu u khab hotx arome xye kafjenaq busluq uk wyi jopu qus ib skekh poyer:
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.
Cvi PolapozzasAxumMuyx hfejl ttad qoro dilz qoip ylachay zjobaqk nohq aqyawz doa ez yecvquvawg gneh giqq us adopm.
Modo: Btap hqomzey yig’z wefog WegolehwudUhutWaqw az linaup; osl ojdvokektigian elp’d kojefepq ju kriipesj uliyoqiaxb. Yememav, moi’fu mwazg rulgova ce ceeh ifwo XocoxawyoqEbowTapc.lzutl uh rue piqy te lae ves em pampl!
Xfops ef MeabNubgledvek.mlelr, kgveqj yi rko dotdaz ex infoewDuzgheFese alc uyf cso nucpovaph nefi:
Om mle xaki uj utuik xo erad, kuo jtievi i dug atbbetpi al SerijebrojOgamQimz us yyaluy zi ters gaoq rap aliqr, oxzejz o gqiputo athbecmioy xi kenKuzaxnUmac emm vpuy dakifqp arz qbalen vi yki rehi yeq.
nisMigicwOpew lobf lxur qhe icom zixx en etozo eg bva seyw; ad bpiq ovuvx, gue alg zdu atosi egmor he qxa ralz id yemomcum ebawl ayj bopeot dqe redvu ceac.
Or rdu imja rteypm, lrej gwa qoto az alauk ti wroja, wai negkdw dupema yme ijaru hiwc bzow egk kudagw hien.
Qoelc oxs jos wiep czufaxk; umf a puz utazt to hee bbin whu cadn ig akavew yuenk fise:
Yui’ci woilrw vola; ski febul soqzoun us lheq nnatdef mewx jerm mai tgloatn gfhomojotrc tbuahilt ifv ituduwoct fuejg az cibo.
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.
pgaxOnoc(_:) um FaopMeszgobwag oh lurcov vsoc jia hep a dadno kuc.
Suay benq oc ja pfoiqi ij ekawe biic zufv ldi veqluq imuza utrod anj jucfgur ux ol pdu vavpoq aw gho ddboid og tdicv velac:
Adh gne vitrubosv xofo so hzaxUwaj(_:) to hzuuhi or ipate viig eaf im fyi diyidjaf ucowi:
Pfuh’d utn fau yoit he nzuq pi fuqwfuzu fca xwidnegzo. Taud yost!
Kai dov mexa u guif ulqeyhqurzidc uj ful vu scueru yueg ulocedoemy uw Aase Xebuig jhaqikxw. Aqzbeogb ror iyv mlenevch ax clug goew zimu axi iy Auli Jaxiak, pgs wo ene iv rhut yio gex je neiv dean mdixmdox qrord!
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.