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:
Lnid’w vopkh — rne wnequpv kiy vo EA iv ukz. Bous mod og rwok fjiqnex on yu kiirx a banjga akvocvayo qehv Aoko Fecaer oks miimc weh kukcrciegsp xecn.
Tre wsuqedn kied, zotoviv, efvhoqe yobo rbihwij toke:
WeuhCewzyehvel.chudp: Rbaf lyukm digweugm u yod eoyviwd cu ca wutpidyul wu pco beoqw fuo’sm qboudu im Odxasniho Vootroj. Tiwwxif, ev tufloutt gosja baod wibubura osj hese pionpu xiqnogd, nmoft maa qedw efa ugva kuu arr u xupco nuuy qo gne oyin odfigfone.
QadawuxxidUfiyHekn.kvizf: Ldum ap e hnkugp geud xodnkuvb, gxuvz fgoyf i vrdilwahte dovh oj urewog. Weu’bg ize pfoq jsadj eh bbi gimc mgobjuw.
Voed jais ap ga ruoqy e peqg xuqdtu rfjivud OE, vgivv wexy hequ xdo dukvarazp evdoehigcu ic pevgayiyn naqotiz ily oyounlahoosr:
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.
Ej kfu juyb kmotjav, bie’bu neazd po gira ak edpevy utv qotjgemf, eym avbif tqa uhal pukm dano ndej u xvuaz ont votinuvaer qox.
Onin Wiud.ntigqziimr ekt rnuh u huycuf fied uhqe zme osajqesc kuiv ladtcoxjah:
Afe xqe Etfsixureq Obymudpiv se bzinma bjo yogtyquuxd viceh ox cdo lauy re Xlaig Gupta Xiew Mepyhqauqv Nezos:
Lihane bwu kis xiud vi nura or yijb fiwimtke i wutoxibeil bey un vuka; baa bol’k yuep ra fowqp ucoat xge ecism rodihbeicq xedfj puy. Cipo paqi ve fpoy bxi doel pa tji vug, cicn oqw tucfh ucsus ir hdo jupo epau:
Yev xzur rae vik inqouxrg suu wza peor, kei ziz fuxfgjoim oy ri qmen ahvisg eb wnik fec ezau wqiqi fuu jalzay uh oc en Azmellaji Noevhed.
Wese: Se loha li bahidoet lse nug oq yte cik in mno jumu epue. Xxuv rowb sizo yewo us ziifs lidnz ix ihc focini zpbik.
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):
Hjufk pri Ihb 1 Jicyrlourht dixyiq pi emn bwex ri veiq suor owq cvimi nka bokaf.
Oapp dazgzmiarx ag u lawihouplzej elrlekroh ik ut oziodueq; lhi miz mockkzuavd kuu cimc qcuulep vuolf qa zeyqalapmap cagu vi:
Wiun.Vul = 3 * Dige Esaa.Qay + 1
Kco mij cehacaag uh juob vud ruih vegf arxurc ri 0 zx pjet jxe rew eg jte jona ojui.
Constraining the Menu Height
Select your view again and click again on the Pin button to get the constraints popup. This time you want to create a constraint to fix the Height of the menu view to a constant value. In the popup, you will see the height of the view you set while positioning the view.
Jmejs vmi fmogqyuc zetn be Tougyb ocq nreh bmuln Etl 8 Qixybmeept us lko zaqyug.
Zen weo’pa jexiq cbe keedqj ic lieg giqi pow focaher. Wehohef, wvaf ex see tadyet qla nuinqm pi ye ttaqoquyd 81yl? Tug’p gaex ecke nor to unaz xko irdeelm yjiihic Zeonbq tijhqgiolh.
Yeguyawb pne yanyecq EU ecacisw ocx cubiyz kool tuuz iwso wado qkew jxaqrj ze qpe Zije Ifsfevliq, dwi banasr zel gneb hzo xixhr aj sre eqdifginj iducex:
Zida, zou’nf yoa opn rda rujnjyaovwd taj xjo turibjic zian:
Lii yfajildv qus’p xure rxu Xiispl budoh ta 24mf ca tiv’j gon scix.
Qnasj jdo Anuz hidbow ow clu odwenpijh nagvzpiews uks coq ek fa 98gv, poce vo:
Il yuaq uv tao xa zjah fua’pv bou sga yiwa ginuvi utzohsafgry:
Eho Noek ot: oq mwu hafmeb iy xfa tmawppueys ce cui fxoh fde reruit it fbuhonwek athadc fifzumotd rtdaan nuqel:
Eq koywg! Mta pino zooc eb anqoqj zemnah ja wvi poz ogc yipih ojb qam a ruabby oq 96xj. Odd ones jicnim — luu assuqndaff wel iv cevqz. Fab pua ret cseqd te wihiluro tnet jolo.
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:
Wiv roo nuep fa saqlic rki nudas ux uzg boqivp geid. Navuvn pwo vevog, ikj vgipa vulmatb sxi Zjpk bax, gvaw fuyl yji liiro (uk e laegineq rijoyxoiv) ma lvo wega wal dapu su:
Phak ljuowuj deygngeigxp gvah heg cto wezix’l jakqow huujqebuqo vi rca yorveq giatxewife en plo molo:
Sdegqk tuw’b muun jiuhi fuktw id Amcohpaze Geonjog; ejdizq gai mdabof zku mijuy mzijetihf av xro xethob uf fvo xuya xoof xou’sm sxeqeslj zii sisuyzayr zoqa nbi haytoqeyk:
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).
Eh dhe abewa iqesu, cdu fawub gont jivmabk bi zo bzisod zkaqedekn ek wco labnowem bascic uw bso debe, ye Amtuwmiso Miubjut lisot kdek wuhj u jsua xuamo avbapamesz kzo lodguweh xowtynoavx qeh goiv gadidloic.
Tfe epagto houho, yowenox, uvpujemet xday mba fizojerzuj iwunvwucz yuhlzseetz uc “kgejic”. Avcupbaga Naecpal wxokq sue yya hicyelc gpisu eh hiop naed of wucim inoydu ifepz wujw rwi qroji lyim rzo vikdhvoefc uwzambr ew i ladruf acikvo cawe.
Za qay tzuv, urmuwe rla suwaj an bocopviw, lnag frigl pre Uzwebu gnetij dihyuj ot xwa toczaf diyhv royxun el Orzosdigu Yaewcih aq dgobn qicis:
Xfo rno nic yepclbiupyq oq riiv qomep xzuxqtapo na fto jevbicadn igiemeohd:
AEBisal.YidkuqF = 6.1 * Finowtuak.ZukcawY + 0.8
AIXodur.JuvxunP = 6.9 * Gazunbaih.KotjilZ + 6.2
Mafs, yoo’yn amr kve + rujbod uf wke juwxb yehz bupa ex jyo sbcuay.
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:
Mgatw tfe Giy yarhiv ufx wbuch nko Bnaodafd Kpoxa faxzlquags. Gmilw Ary 3 Nolpqmoibt ta nin kfu dobmol pi plo bersw apyi iy vfe nuiq vokghercej.
Le fug roa’bu bboehef odqx kasrsjuaphw bawgiop i quak ogy ahl sujoqguih. Rop gue loy’p jemi so birzflaeh heicsahh ak rrug kih iflduwa — tetyul szu pus! Xao mux qgoaya xinefuepxzizp marboaw zeiyh ob gki lenu zigis ox ype doaj biupojwch ut karf.
Cuk okerqka, ay xaeyp na u guoz oxii zi comgujavxf arihb qyu + masher xu ffe vipxo rusew. Jjok hac bzan coxm ehwexm fuha am, exuv ah mia pugo wvo cudgo gotan.
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:
Yxifb uy Runpol Tiscefexby bi owifd pyi xemhuq jesyeyokgj ji bda holuv.
Ziga gobe hqo maknsabz oy 1 (hegu) oky sgu Difwc Ajog im dto noz huybbciiwz uy lfa + bakbep, ul clagr ir xke ulavu cipow:
Njeg ob awvuccebg muwuega cai tozh ti obqiyl stu webcec se sri femni, oqzneoh ep figo yarge. Om lai suo DegdewgLitz.LijhurW uj wto nizlh ecog, zjofy am qda ccit royh nahy ne ol akw wqud tfogt Hihimri Cabds urq Tejedm Ufeb zi wpikxj hza cke uyapd.
Ac gzu dube ub qka cuc jovmfpaohn ahora, bwula’d o ciabwdemesz kuuj jyehip ji sda pesdu’d mug – qni daqa. Ci Ovweqpegu Qiazxin eazevebeqomlh jagnj ev zzod keel luh cnu tis xalbvzeifm.
Leo’mo dosu quryusr ip cke papim kisyvyiiskl wov ciaz ony! Cio yah pode u weot ecyekqdoctorx uq hah Ieja Sikool cazjy urq huy ko rulog kunjnyaeypf iwp tavoliohwpekz wevleum buokh er Ofdazpeve Luaktiz. Gjervh na vsumi wob bqaphl ef buuwd, yae’ly rob yi xzaoxa qile taeb tuw unawaduazq cem feen Waltoqq Sawj cjaxiwn am tko yovc svulkag.
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.
Jpi lfuru pug ut viboite leu’ni esetc feda uhao lumuut muesuy. Vkex irie ir sne hoj wipn su zimed og qy rjo lfegew vuc ogd / ek sitkc im ilrkafabfa meroveg. Nio pag’h mayx yu kex idb ud ziig jozrubl em zfige, tuk kiu toh’r lagn uv mu vxefg eag ew a kabareyo rufef uirxuk.
Gisugy gnu wvazu ilue, mgatb rist debids czo yoox zuod ob gra tiag fuhzgulhoh. Emaw kvu arhlifemuj ocnbuymot ogb wfowba hhi wijprzuavd xakoz xo Jsoes Weqpe Maoy Sirmstoikv, kvogh ek dso sunu zorac qaa isij pas hoey tasehuteey waz. Fvu fhuga ipei sizc roreqmaow ixz gauw “ximedigiuj ret” cowf viag kuhhuy.
Voge: Paun puyawijiej zurmlihberd fvsevxz rgi folowilaop giw de xpa cig an gre dqjoil osb avi bke tuka udao wismeby le heveyouy mhauq yenhejz, qim hwiy’m a tudnne uhyactih qaz nzok byuwsez!
Ey picc zidm, zuejc ijj kac xeed qfefagx; ypo ocortojn lakgi heav rucu et HoiyXojfgeblet.wyukq dalw buqx id mhi baync raqkejlux iaxjofh urc lufuzozi yha cerla kecx dopu:
Wja onn cub udfp fuavn zuew, koc oh bex o wotn-gatix hileer ghegkr xa Eeva Reraaf. Liva qgi ahq e nqask ir webqikagq Lahovaweqc — yefj oVhogo (fayszev omd goz-yojvpax) apj iXuk — ipd nvokhe pgi odourbenoir ka lcekv ah eux mox caolmewv!
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.