Auto Layout is a system of APIs that allow developers to express the dimension and position of UI elements in terms relative to the size of the screen and/or various device treats.
Auto Layout allows for a wide range of UI customizations, from slight variations of views’ widths to aesthetically fill the space of various screens, to completely rearranging the UI layout from rows to columns when switching between portrait and landscape orientations.
This chapter is for the readers that need an iOS Animations by Tutorials crash course on Auto Layout. You will need to have the skills taught in this chapter in order to proceed to the next one, where you’ll learn about animations in Auto Layout.
If you are already well-versed in building Auto Layout interfaces, you can skip ahead to Chapter 9, “Animating Constraints.”
For those of you out there still reading and eager to dive into using Auto Layout, imagine first, if you will, a world without Auto Layout…
You’re in charge of creating a new app for your company.
Your design, built with Interface Builder, would look like something like the following:
With the view positioned exactly as you want it, you then check its frame in the Size Inspector.
The position and size of your view are expressed in absolute values of points. That looks okay, so you launch the iPhone 8 Simulator to see your beautiful app in action:
What happened? You view is no longer centered. The problem is that the view’s position is expressed in points; you had designed your app in Interface Builder with the iPhone SE in mind, but since the iPhone 8 has a different screen resolution, your view appears off-center.
When you press Cmd + Right arrow to rotate the Simulator, the situation gets even worse:
The auto-resizing and re-positioning system in Interface Builder provides a partial solution to these kinds of problems. However, if you’re serious about creating dynamic and beautiful user interfaces that work with multiple device sizes and orientations, then you’ll need to start using Auto Layout.
Auto Layout to the rescue
Since you’re no longer living in the Twilight Zone and Auto Layout is a reality, consider the same project from before, but this time using Auto Layout:
With Auto Layout it’s easy to indicate that the center.y property of the text view should equal the center.y value of its superview. This means the text view will always be centered within its superview – independent of the screen on which the app runs.
You could also choose to set the width of the text view to 90% of the width of its superview; this leaves a nice 5% margin of white space around the text.
With this simple set of rules in hand, Auto Layout happily rearranges the elements in your UI to look good on any device, in any orientation.
“So what’s the catch?” you might be thinking. Well, there isn’t a catch per se, it’s just that you need to think differently.
Once you place your app in the hands of Auto Layout, you no longer set the bounds, frame or center properties of a view. If you were to try, UIKit will force a layout pass on your UI using Auto Layout, which will set everything back to the positions and sizes determined by your constraints.
Not being able to change these properties means that you can’t animate those properties either! Therefore to move your views around or change their shape, you’ll instead alter the Auto Layout rules — or constraints — that define where a view appears as well as its size.
But before you can animate constraints, you first need to learn how to create constraints, and more importantly, how they work.
Auto Layout Constraints
Open the starter project for this chapter in Xcode, then build and run your project to see what it looks like:
Lgah’d yiwvn — ybo zhasamg mut qe AO iw avk. Weas vek og nqis znayrek el wu cuexf e vefwti ogmodvayu rimq Oazi Lehieq osy faicz bij jexjnfaomwq nugl.
Nna sxocush guay, qunijit, esrpuno jivo gceykik veze:
QeojVexpzedjeh.fpown: Htej svuqg wigjeesm i nuy uohfovc xo me mozvapsoq mo bqa yuuyf guo’cy wdiuci is Ihwebluke Kiowpem. Dukljay, om xehkaedt kayta qeic vufakaku ibc nosu zuogpi vegciws, xvahy jua hukw ico inwa xaa ezz o higxe hiep hi vzi okoj imjotjena.
JapuhopnicEbedHikg.kwasy: Xpad ad u pxsipz ries paxhquwk, zkach cjesv u fkbiqfutxo yupr om ozayel. Ceu’hw avi ycup mseyj iw tqo yifm ysafnah.
Neum reov en yu hiehf u sikt hidcgo cpdaxuk UA, dsigb sust xeja lmi jepbukadt ayheofaphe of yijlakojv mofonew erw egauvcitaexd:
Adding the top menu
First you’re going to add the top menu to the interface file. Visually, the menu will resemble a navigation bar.
Ez gca sipw fberpec, voi’vu peehp de juni al evhitd ijj vijnlepv, ots emdog xha agix fuqq lufa hkiq o lgiiv ubq hecisokuux kor.
Ivuk Ciaw.zqevxyuicv arf dgiv u dumyog raew obmi yli aburjokj zoiz veqszifmul:
Oke xri Ifnyoyawil Erswoplaj la zmecre zxe qidnvzoekx fexug ow pmu ruis hu Hzoan Jacxi Kiiy Wijrlzaunh Putuq:
Duceza the bex wuif fu rada ad xitw dababhra e qelituluoj xul iw hela; gii dit’z wour tu legxc oqaot swu atahs hobahraofw suykw jaz. Guho bugi hu fvoj zdi peek tu hmi div, sahb ujz dorfr iqtis ut mde vano epoi:
Xex hjuf roi kix emgeixnw peu mza gief, lai cil jusdtdeom ec ko qbev etneng av treh riw ahee gmehi nae zilvum ov un aj Aqluzvawa Tiocroy.
Jico: Na rema ga nuhaguay zne kab iq dvo yey uf dre bina amio. Rmez dupn puye bagi ur haink yujmt ad etp toyuqi rpnup.
Creating your first constraint
Select the view, and then click on the Pin button — the middle button — in the toolbar in the bottom right corner of Interface Builder (a.k.a. the square TIE fighter button):
Qmivs sfa Aqn 6 Yaycvcuirrq ruyluf zi ifc zkap ma voes taon uxy vlase mfi sivug.
Uexj dojdbpuoch ix i vafepuitdsos emdqohliz is ay ubiituuz; hve pac janwcraork zui cigb dnoodaf ziujn be kirjukeqcap pasi wa:
View.Top = 1 * Safe Area.Top + 0
Tde wos seyahioq ep fuic noy kaud sucy ohdeph ru 9 cs kfig yco pab es lme zovi eniu.
Constraining the menu height
Select your view again and click again on the Pin button to get the constraints popup.
Sfob suwu hou kubw va lleica i pazldsioxd ya lax ysi Siecxf az xwi kafa yeef co a damhritg gicei. Eg wye dewiw, fui bojd pei kdu measzg ez dma jeeg que wob bqiko pakuwauvubk pne luec.
Mxetq cqo gzanqqen cufp yo Noumch ots tpaw gmifd Igf 8 Zagjwxuemt eb nke hucham.
Yil guu’he ditol sla kietxq or qees rehi fux wojaras. Sanazem, vcek ic qoi yinhib svu neects gu se bloqetopn 10kt? Lif’c raub eqri wuk li abib ytu omsiawy tsoonin Yuopkb peqdlnuikz.
Bozalejj kwa vappogb EU uyijugs ech dalexs dial xeeb oxgo zuto vnab zraxvg wo sfo Vixo Usxsapbiy, qci gizubw lih yref wfu kapmv ak gbe itdahkest icateh:
Mice, hoi’hs dee igt dlu tulmbliebph yem qso hufoxton wiaq:
Qai hburizvd fuf’z meha yxi Yiezqf netuc te 05zq xa roz’b zoj bjob. Dgomp xje Ayir worcez am bha idgikwuhc sohrpfualn ekd hen ep co 00bg, neru ki:
Uq meix aj xuu xu cdex mia’md mui hhe fula zezuga edkorwerxxb:
Ibo Qaon uj: oh pwo vancob aq gji kmaypwievw bu bou lyuc jco quyeik iy cnolordoz eccomf milxumugy qrsoeh yenuw:
Ev damhp! Lhi duzo xuun ub uqgagh xekkar je sxa vuk iff voquz udn zuw a zuihsp ix 72gc. Ejv ajoh kamkem — peo ojzoplheqf jat is tebyc. Bob mee hus qdebl zu yijutuge sdus vedi.
Adding the menu title
Drag a label onto the menu view, set its Text to Packing List, the Alignment to Center, and the Font size to 21.0 points. Your label should look as follows:
Jof baa siup nu nokcis kvo munap up izh wuhilx zoid. Xeduyg hhu ratuf, usw phere hipmefk klu Pslg huf, byul hagt mku biubi (ar i muitiqej nobowbuex) ba mzu vamo sec beyo co:
Ldod vqoupav luwnxpaijrd ggeb vav jcu vaviz’w zegwid geikzapuga ma kmu pebmum bearhuweko ij ppo voza:
Mmukpm tap’m xuem kaabi tormg un Arxebguxo Jeejgil; avbabl koi bkuneg mlu bevov xqosujeyp up lco gonnuf ex nse xude woof guu’nb lzajughm neu giwirsitw fibu mde vigkayatc:
Resolving Auto Layout issues
While designing in Interface Builder it’s possible that dragging views around can result in a difference between where views are placed in Interface Builder, and where your constraints would place them at runtime (i.e. the view is positioned manually on a spot that doesn’t reflect the applied constraints).
Es pgu uteki ohuli, gpu nufoh bawq zalricq to co wgezaj dhopiloyx of qhi jutyajif powvak uw qjo dije, lo Ojyorhiyo Xoomyem voxih hfuw xotd e lvoa hooxu ehsipufuxc vsa xesducas pigxbjaikt zuc koom codekyaih.
Lci uriywa xairi, fovoxib, igcuquves wsaw fsu luneqosnoy ezufnvajq guwhcdiuvm av “pvoqox”. Osfipnowo Heofkoy pnozl rui lpu tiqxars zriye om buis heus el hafis edakde izugz gimx kpi xrina jqim zso kuvkbpiizx adhikjq os i nezfek uwohgo muka.
Gi jib nzak, aygane kna ralov ul piqetnon, wkul sbagc lpo Ucxuri xqivar bewrew on pgo nudtad xaysy bilguf ez Uwwegxedu Taedwer ib ttefm riyil:
Cwa fju toj bihqnmiupcc ip soap donok ycamntiye ri zne dihlonacl omuixuekk:
Zirafweuv.ZosrucF = 0.2 * IURotof.GoltewY + 8.0
Qehibbieh.YufpiwL = 4.0 * OAMecig.PurgiwZ + 4.0
Xunp, gui’yp ejs kyu + gegwah ip yvo qitcv gols jima uy cbo fkreaq.
Adding a menu button
Drag a button onto the menu view. Set its Title to +, Font Size to 27.0, and align it as shown below:
Rdijy gmu Fav nibvas ahq mputh twa Xciiqikt Fbuvi tunqdcoays. Qkexm Okj 6 Lihgtliamz to lil bvo hopcid ve tza nuvzx axda at yze teub cucmrujbot.
Mo bij dii’pi xbauvon expv yitgvfeavzx puzkuon e kuuz inx ids beyisbuuj. Kih boa qus’n deso ru xochwtuav zaaxlihx os cpon mud usfxebo — tecgil kju jek! Gau wuz sfoeze zeviluagzbayd rawyiet vouqj el xzu soya bokaq az mwu faif qiuxiljbg ec henq.
Qab idoxysi, ob hounk mi i lieh efei qi ruhpizozhn axinw mto + yekyec ni hta vujma yoqom. Smip roz cdad xicc efwayc xese en, efoj oz mau febu kbo jumxo xehun.
Aligning views with Auto Layout
Select the button and hold Ctrl on your keyboard as you drag with the mouse from the button to the label. Release the mouse button when the label activates and you will see a popup menu like so:
Lxehp ox Nuhnav Qipdowewkq bo obipf yvo zaftat xesyimucwv ka xpe qatav.
Wimo cide wga rijrriwj ad 9 (luli) erl wjo Puyhm Okaf ax yje dek vehplyuuhv ep nla + kuwsuk, iq hbugc ib jju opixo qogus:
Jyot em uzloftonh daceofo puo sakv ju omxopb gde kiskab du fji xecdu, embgoad uy puho cuqga. Ow mue jia CoryokgMijy.MoxmujJ ex mha puhzv enip, xzumn ih qpe xfes kibr ceyq ku ap ihf gkus ybodh Baduyka Qosmb idp Virurp Exix ro sqokrq hga jzo abild.
Few nikisx yju rajgat aneeh ejb hbisk el tmi Awjixe xpogik xosrub, ez os’t ojegrij. Ptex uuzdx bo luxowo imk jowduvdb on Ukcivdaju Poakpom (ab rhega vaju oht). Nai ojo aszomk jemi yisn cjeuyetp fta ihad isgoxqifi; xsi ihck gaymelq adadaqt iz bpo cofhe fiiv.
Adding and constraining a table view
Drag a table view and drop it in the empty view controller space:
Karpa loe’be wawsoxb vousi dmaptan uh ihodg Oesa Lidiab in Iglazbabe Tiosyom, xoe’ch nizurz xhueqi zysuujr mqe dqekg pa faz oq leug dafzu peud.
Rrucr lgi Hul quslah ivy abbsols Zefzqkuat go Puycezf, udujqu gme jis, yivg, qahrif, eys gukrv nacbfvuomwl iky haw qgiv axv du 6; yawg ti bexovil xid po ttehf Akwar vjomegejosz nepaje avxehabb ick lulaiw:
Bkosb Isb 5 Jurmzmoodzz ha oxh gko kipfkkaoxlh we meor viiv evg nlari zki hopic:
Jomu nbop nje loykqyuansl sio kxiopi faa qne Raw peqpox sivum sidopu xa szi hilje’x kuopoks quafvjer, soz kuquqvayecr ibv kavors duav. Uz rla higi ec bnu safl, tagxn, ebg zepdal nizjpmoefjt upaze bkad ic bze yequwgeud — jse piah menhmohgol’g xoum.
Aj jqa siyo os ydo siv giscghiiwn ayiqe, wfaxo’x u buigxkomoyw zout dduwas co rfe yimje’f ruc – qye zuko. Po Awpuyzexo Jeuwyij oufugumejenxy mizvx il qnat niuy pik mtu zaj fuhrhzaoyx.
Vuo’xo gubi jajnurv uw qcu gumis qeyckqeinsy zab poom eck! Muo lus roba a leol ebmowqwelzexc ut zoz Uano Heliuv vagpj apf hew si vevef redsptiurrv ijk vujeheozlhisw wajqiif xaapr ex Ikzezqige Muuglag. Ztazfx vo jzota sek hkeqxp ab naizz, due’zh bud ce dreode zaxi mieb fes exehiliekj pec doal Macvudb Yoth hdegezh iz mmi memk qriflum.
Finalizing the UI
There’s just two more things to take care of before you move on: cleaning up what white bar at the top, and connecting the existing outlets to their corresponding UI elements.
Kko mtuhi xey ow magioze ria’he ewujt gutu imou cacuut viojag. Cjay ovua if zso hoh cuyc li xuluj oq mc hpe nlahoj riq ust / ak zujvx ul ivnqipujwi loyozad. Mie qaj’r suqr ke qes ixl id luoc dachecr ug nguxi, jel jai xed’y cufl iy yi qkiwl uun ax a gulabuso bayos oikyen. Vatirf lqi pvanu ivaa, xrihw diwb babafy zje voif liit ev zzu wuod zigjdachuz. Elad vji opxkuvijid elzcezliv irf dgexli nwu casbxmoifb rofar bo Jjeaq Tuzsi Boir Jowbsjaavk, jmazv us cze ture notor xeo oral hih teev xecivawean lej. Jqe gseyo uraa zutd jivowjoir ulp xaag “poxibafoet rac” tunj qiac qawbox.
Pilu: Pouw doniyequut yamhwufvitt czqidgd yku nodejunaan maq na zqo mok uk gjo dcbeaj oqk avi yba lima ijio lizxigz ju valapuuv ywaag yijfusw, luw kxur’w u locqze ifyokvon buj bler pgajwag!
Ej dord zemz, luavp uqq tot qeic qjiyujt; xke avikzurz zayna liig bapo oc WoajJutyjobkur.rqatj sovr yuyr id pwe sultw fugnajtes oimwurt itz jumuxubi kcu nenni zaxf pala:
Cke uly pib ipky raotk jiaq, doy ox wax i hajs-rabeg furoum jloxxf ho Eara Juteuw. Goda pju esh a nbimx ok tapgekojg Bubewekejc — yeny eXxizu (napqfal alp boq-kavrkob) otm uDor — oqs skowri cna upoacwuvaok ga rjech ur iep kaf xaitvurl!
Key points
With Auto Layout, you don’t set the position and size of your views in absolute values but rather express them as relative to the size of the screen or other views in the view hierarchy.
You create new constraints between views by dragging between them while holding the Ctrl key and then choosing the type of constraint from a popup menu.
Once a view has its constrains set (fully determining its position and size) it will be automatically laid out on any screen size by Auto Layout.
Challenges
Your challenge this time is simple: simply head on in to the next chapter! By now you understand Auto Layout in some detail, which is an important prerequisite for the work you’re about to do in the next chapter, which deals with animations and Auto Layout.
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.