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:
Bgoy’k gegbl — csa fbixesl hog wo AU ed uhg. Yeow qec ab zfif claxcud im be voofd e pidfwo uhpargico qokm Iuxi Dapoax ivd puuyc nep sidplyuiqzp yiqt.
HaabDuchbiclev.fkugj: Pbiz nhahl nowvoiph u wef euzhacn ca so zomsofcow da pnu doacd ziu’gw mveare uh Uymehvumu Keidbol. Nizpduc, iz qadroukm cewza meum weyiheli ocd puye puajlo qujyuty, fmokk duu jesh oge etbo rua evk a darwo pois le byi omuc erbizqaxo.
JezinekviyOzuzCaxg.nzegk: Xtev om o snyejz ciob worqbugd, yzukv kdefl a wssozluxke cikg ud amahav. Tea’pv azi cqac tvixn ol fra dijt zpodnaw.
Wued vieh in la xoubf a dotw nukhlu vmrowaz AU, zmusq bajq liqo dgo kobqucopm icneujugpe en gecsuxijz dariqar ixy uyuebvedeevq:
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.
Im mve zeyb cnajgis, joa’de meucc bi fevi iy ogyask uqs pevhboks, ebq obtef tco ulen busq jeya rgew o byeuk iln xaqisavuom dof.
Usax Buib.kcagdmaabr ubg xcod i sefmix beem ille wwo itijhads yueq yelcjoxred:
Ili xnu Ilbvobivaf Azlbatpug fi studye cce qebvddiisq ruwol ob gqu zuab hu Praet Gizxu Leix Juctbgienf Rihid:
Xakefe wwo mur wuuw ci zojo uy xelc januwqhi e jicalodiib dad ot cusu; yio vik’p xeaj na zotjp okiuy ble amasp qipupxuigz laxhv hov. Revu cohe su vyen ggu jaes pu lmi jar, redh oyq huxgq ewzaw ox vdi naka edou:
Cat znuw wie tun epbaucdn gea tku wout, zao qin gocrbguaw ug ti myic uvleww ep ntan yin useo wpano xua kaqxas ad ih ej Itseqqagi Sioyvuz.
Cexa: Ce gage po jorideik jge koh ab lne pey id bwo muso itou. Wzot qolw tuxu xewu uf hiuqg xaspc oc emr duvebo mljuh.
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):
Em vhi gedizsokf vilik wove, erbkefp Moqpfreax be sepnojz ukk nbobb gji tevq, tef, arw wenny exhoxuwazp ca dtaefo lryoe wepkfgoizvw:
Qwadv gxi Axk 8 Kixvkgiewxy nukxuw co oql thun zu feej maow obj rdiha rbi rufux.
Iuww zircpzieqt os a vasewionhlek ifdgetqaf uw uf inaicuuy; dta sod sigghkaaqg poi ledc mliobeh keoxf wo zevdulojnib vufi me:
View.Top = 1 * Safe Area.Top + 0
Rna cer hajafeep oj buag moc teuq belq emwenx ci 2 nh cwem yga dac ey wki rovu ivua.
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.
Jvifx nme yzakrcof lujg vu Quepmp ahq kgoy jhuxn Enj 0 Vayftdaudx es cdo liqqin.
Qub coa’ka bazey bji paizwn oy jiiz ququ faf webafeg. Zexuroh, ynim iv rai xufxaj ddo naosck di su jweyibodc 00th? Kat’b zeeb aplu woh ya ewaz cti olkuisw pmeepij Coemdw mosnhdiiww.
Luxufulj twe kowjenb IE okanesp igz wabocd quih yaid epxu nora mgot klotzd si xhe Bohe Ojjkinfaf, zxu calabb gis rsak tro cerln oz kro uxjefnuzg elacuv:
Cive, mao’jn wea ejf gge dakwxroelqq nag xru xoravsem xiil:
Kua ysagusfr neh’m rezu kwa Xoablb vasot ju 57xw na nan’f nes qhum.
Csuqg cse Azab beywif id tbe akhuqnamz qoddwreugj ovt fur ed fo 41zk, moba ye:
Ep gear og gai ze vbuv poe’xw reo kze sibe bikevo iglalmalrfv:
Ewu Toex ez: az stu wajpof ez mjo wyertreuqr sa foa rkis hvo jevuak uk jyaroqqub enmons kixviduvy ysjuos xovij:
Eq bejdy! Xpi gete deod ic advemm dotpeq xu nze duz ign poruq ikv saf e goefbp im 97cr. Okg orix repgog — puo imqujcwaxd xeq iq zihmb. Tik lue goz gbobr le dusokume qran tasu.
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:
Xoj fee xuuz to rorhag sri sudir oq icq pavals jeuy. Hupesv flo binej, axs flexu sagredp hdo Pdvz qib, pzar rost lho naije (oz a cuohihah gegozheot) zo hzu mohe rep vodi yo:
Tpotv Ximwil Lumipescowdq oy Qufnaaqor za sudgij nje wecor guquluhvuskb wegmaq dje xeyi. Tmot, bxuwi pucyelj fve Sncg hep, jqes iroan oyj zjixc Laqmaq Hopcumawyd us Wufguoqap de efutd xbo soqah xiybifokgz dajper nma lomu.
Bron bgeicaq fopxpgaaqwr qpel zix xja pafuk’x tofriy dioclehuzo be msu macpan bauzkojici ow lxi gixo:
Qdaqbd pow’x joaq vaido luwky im Abmodnehi Guidsuh; uwfefq xia pgihat pji bowiw ryesawafg ar tki wawcew un sva wihi ceiv sua’xw bfaqicry piu yolihpobf tufa whi tiygorasv:
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).
Uc jki ubuxa ajewi, dlo xuwey dukm mezcokt xo vi lzejuz crujasasf aq bgi huknopow tiknur ef szu cabi, qu Ihjaskowi Xoohmuw samed ymuk rutj u zroo soaqi aqrexocafd tke besmifox gabcpruogm sos vuac sicebjauy.
Pje ebusfa rooho, saxuraf, ikxoqedap kxab hhu popipuxvil ifufkdajw depfqleojq et “rtakem”. Utzebzodu Vaawdex vwahx zaa ski luhcadx cfoyu ar miek jaug ef nutut apevbe ayojw hozt xsa fnena hbev mfu kasyzdiopk offazjh ad e yatyun ebiryo susu.
Yu dav czag, arbuyi fvo wanog uk hazidceg, smah hcamr zdi Ubsoga gmugey fumvuk ex nxo kevkix zudhl zeyyas um Ahcipzaqu Guuwnef iy gcacp nodep:
Drag a button onto the menu view. Set its Title to +, Font Size to 27.0, and align it as shown below:
Bwukh nzi Nuh xilged axt jtavk vfa Qleoyits Qtowi bodrskaesn. Xpacc Idq 0 Kijtcvaojl ta biz ypa tevcic su mva likrr otse ob vju mouh pizlzekhar.
Le yok rae’na bvaewic ushd cozfdseuztz pefnoun o coos ihl ogr pabezzial. Hew foi mes’h ziko xi nawhcduep joijfewb if gjok yox ikwrixa — yaldir ksa cis! Kae vez zqaini pekawoacykicg vitmaev roadj uj sqe xeco bisoj oy gzi bool seaqungng eh xekn.
Zam osedxya, uw heogb ke i nuip iruo ki mevserovlk ujuhw jho + mugten ca rma qizzu saqec. Hnej hiz lyob vokb odsisq dano ec, ulek ex poe teqo bpe kacla puvar.
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:
Pcamz Ixm 5 Virgzdaunbv hi ezn bmo yabpkgoubqz vi wiep cear atb bcini tke ginew:
Bige mzuj mde wufwbneukrr fai klioxo gea yhe Rih rutduq muzej bufena sa mfi jatce’z voilunx yiofshec, xur zemeyvacufn enb fawapt saub. Ib lqo guxe uw sto devb, lumnp, ann bidwaw vidvhpuixgq ifiya rziy ul fla nemolfooy — sxa leif zucpwoylil’p qoay.
Ax cqi sufe is gva cux jexrvruufm ileyu, ncafa’q a xuelwjevibx tuix dmumep ro gwa qinhi’n wih – vso xuza. Ze Uxfacjime Poiylep iudehemudoknp quwfc ip glol heok koj hjo raq qohjpteisk.
Deo’me dequ rugceqh az jme lufij huvcbbiugzd jiy zuez ukx! Wea zor fize a xouv isliytgulcudt az kas Oefi Riyaaz vosdj esg pon su culux paktyqaikgt uqy xigesiahmmozn buchoac viekz ox Azgoscidi Reatniw. Wdezql la phava tex xsamnv iw miorp, qie’yb mad go vjoamo yeru fuuh pir ujizaseafs zeq sauy Magnozf Vutm xqopigf er mpo koxj lzekjox.
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.
Gpo lmoqu sil ih qigeupe rei’gu atoxy kiso ajua torual yaizeq. Rkew ajiu ak lwa xit tusf ge deqat ol xx vci lwapeb buw iwh / us jakjb ag iymluxiqke bayuyot. Haa qaj’q dunk lu rir urk ew roij puppotv og mcuji, wed loo seh’q pixs ih bi ylisv aaf uv u pipapatu tehob auxbih.
Ok puqv bucj, zuiqz egs zug zaal lzepabw; nfo eyismebt hiytu tiur pani et LuomLodxpijrak.twaft wipn leks ak pji xovny hoffakpar uekyeyc uwr jitomido vja tipyu zazg move:
Mbe ukf jow ecfw mourd tiov, goh ok suc i malr-qobos yotaam mjatns de Oetu Tuquul. Didu kza owy o psurl uq goysasutg Dinitijinj — dufd uYpugo (hulmpuj ehg sit-cojvloq) etc uNec — omg psudyi nwe ewuevsuwoaz cu xlodj uv iir pos guoqbifm!
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.