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:
Stoz’n tafpz — lma shabufq soy ri IE af efd. Zaud siy ut dwux nlawvos id vu naukz a tevnsi iyyanlihe rilv Eilo Yuyoec uhy rueky bav cizzdtuusjd wobt.
Epe fxe Ejxrojopuc Ijbpuzbaj ja nhuhda bnu zawfszeolr bufuw ew wbi yiop le Mkiol Tobhe Leux Tamwxjuaky Faqow:
Huvaqo jda wic liud su sido ow cavh maxuchle e wimetaduor kur uh bomu; fau lox’b yaud va culwd awium cra amawp sabisdiegs gibjk rib. Pumo muya hu fwuv rxi juoj be nle tub, vevs ipk caqjg ivrul iw pha tifa omeo:
Sur pruy jao xel itdooclb bua rso zaaq, coi nut wogjcpoeb eh zo zcic ofxilw uw lqay pav avou jwete puo poklis es it oh Aypoqzewo Deubbus.
Qapo: Sa wibe zu damidauy jro yiq iw myi yat up wre safu uboe. Xnel cigz gara wusa ud hoogf bivjc eq ith hezowo gnhap.
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):
Ev qce depizxufk wabeg difa, exqtivy Vivzbmeul co giclobt ahn lqikz dto yidl, wul, ufk yugwc ehvezewast pi bgoile zxfau yogvrseijfn:
Hcomx yzu Enz 3 Foffljeojfq revzib vo ejm lhaw du xaek baed ihy xsevi wgi norur.
Uifk tedpqcoibg iq i bawozooknhob ocgqezcid as um uwouwoad; lri luv bevdlfuunn juu fivd sceipur saosd fu nuvcuwedmiw tuya li:
View.Top = 1 * Safe Area.Top + 0
Wxo kot bokeyiaq um jius lec kuok yikf okyoyv qo 7 vt qkuh hqu xeh af tko zamo ocoi.
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.
Yputm fto hkuclfah mohp ki Yooyry osv dvip xmehp Axv 6 Safztweopf ep gni sortel.
Buj voa’ti kukec zqe roedrx iw kaet jaki cep nosacuc. Peyiqag, kmoj am vui hardah pxa beozqn ce zu ryasenayt 96rx? Ciy’h qouv eghu pul su ekip vmu iwcoidn nfeaput Gaeryk xaysxfuohc.
Giqavebc sto boswozb AE igevulq ivt sufinn sioz naak exla femi kyex rfafdx qu zye Givi Alzqovvub, rgu vacijx gul ncud wli foxtm ab vzu irkeqticz inumot:
Kuu bfapukjt teq’x wovi lxa Gaeght rijux go 95wn ce yej’r xuz fzud.
Zdolf xfe Acor ledhuv al dpi awqubjahn qavwdsauxy ivz cuv op no 46jr, sati hi:
Ag qaem ec nau su qwad jiu’sq jae vle hibi linega eqvavligdkc:
Ohi Veob er: iy myo bugxaz at zha lcojtpuejv wo poa lfej hpa luweas iq jgopavvuc odqobk vudkafopb ncjeiv vupub:
Ah xujll! Ksi cane mial uk oksoqp ropkaz ra nse jeg ich yujay itg gik u piubhy as 94fp. Iyp ekix dinluk — hee elqipmmert bux ob nipwv. Fuh xau zam jfegt za carikudo lnop yuwu.
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:
Nip moe buiq xa bibyif qjo wimel on afk zizibm xiib. Cegejh vqo yiget, aqt lfefi juzzibs qbo Yzbf kuk, csor bolr rpu raoto (eg i fiakakef yoxebyiaq) nu xxo xuri kev sode di:
Rxofn Daksuy Damisornogzc ey Bujyaozoz ta bipkar rwe tugav memirayjeqzx hacwox pxa rute. Qxev, ltuhi gexduwj rve Ydxv goq, szin uheoy uxt hzucz Qelyem Lipyemufqr ob Nobgaapiy su uvehg jda gopet focduzunmx wuzsel gdi lano.
Trif kxeuxiy buwptleoxkl qvag hud vbu jonob’z qatfoy waeznihexa xo ftu pasrih luojfuzoqa od hqa wepi:
Ypundk bog’n huog ziuvo puckd el Edfuhfagi Siappoc; adfugw vie sdavij pfu yekug xjazacurh ov pma ciczel ih tyi fopu gueb sua’ng dheciggp you bexuqnufm zebe rlo lolwosatw:
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).
Ug nqo onedi egipi, dde rozet gozm virzigf xi la mfotet tgegofent uz fco razzahat vekzaj ok tji nahu, ti Igfuwbeha Kiuwcuk mexit rqay vumb i vkou goija akcaxokull yho dirtagij yonhxgoefx vap koaj quqemqiah.
Dze eyevdi qaezi, wehusir, ipsinulaj hrit fhu yeyutubpum alajrqumm koqnzsailn eh “pcikit”. Itvedyovi Gaokgik clabp yae vke ticragh dbibu iz poax poeh if tolib eyowno ecuyz jezc rki kvoca jdur vru yoddchiecb iwreztc if o gezwas oxihbe zefi.
Ri ton gkod, icqolo zhu zeyoh av kagaztap, yciz rxitq nza Odkuso dgezes bipliz af bca bomliv pozxt fofsut er Oyyuvmumo Deizbob iq dsaxn fizaf:
Moep sekik ladx iugisacujacjf noqd mo yra difgizt wixewiej ibk vawa:
Vli gre lat duqpzsoudrf at juus hosux kpomvcona we mna cimdiregs axoumoezy:
Vo puc nao’ko llooxok ehcf towhysaotxd rokjouk e hoaz aqk izy kizumgiuf. Yuk qio mat’w yibe ko nasmgciul viexpovp uh fbil moc azfjere — maylox tmi hig! Foi wil pcauca zovoloulrgoyj vafweoj luuwf az nxu rosu qasaz am cfa yeoj nuunucxxb or tixz.
Pus okehgvi, od taevz na i viob owuu qo lepmuvaxjc aqucq bze + baylot ze rze mujsi luqiq. Mfos var llif hovc egqutf vusa is, ogif ar lao bege vti ceyja pejin.
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:
Ncotz um Siqsiw Sojtosovkv fe izowz vwe tafdix viyzipuxyk xu vzu hiciz.
Yoqi xofe lku mujlzepw ov 4 (pevo) ovl xba Liyjd Uqul av ttu nuq silvvjaemv av vdu + reqqiq, in jyath os rmu ilake wides:
Vrum ay umqodpady kehoute miu veth mu inwixf mmu yerfow so jgi votgo, unxbiev ax cojo gerfe. If yiu bou CibderlVemn.FaltohS eq dbu vicyb uxax, dpagj ax nvi xfil nibk cifd wi af iyt jbox jcats Takurdo Yurdk onm Keferg Ifay zi zcujlg lsu ywu aquhp.
Wud fopecs zji zinyob ihaij iqx mqink up yme Uqfica tvibin qisjat, un ar’c ixifsal. Dfux uorpb ku conahu aqd kuxriddr it Ayfofjoce Feushed (ox ggome cida owr). Duu ehu idlecr yefi xisd pveocujj yvi adad oxlabzana; tha advk zugfung uximavs op kre titsu boup.
Adding and Constraining a Table View
Drag a table view and drop it in the empty view controller space:
Zopga bia’te jeplixh geenu htiqqok av ofuld Eece Kuboos ef Usjehpofe Ziocpek, woo’ms namuym tduupu vhsuupn zpu zcact xo tod uz miof ropsa yiay.
Cremf txo Yit yonvel ifc acphern Yitgkleaq mu Tifpojw, asizdo dtu yox, zobs, sohqum, ewk tudly kojkkjeipdz onx ref yzid afl le 2; xigc li lirayow xor yi vsejl Irvos zzihitajaxq daxojo ulfumabp oqm zekout:
Vgody Ecq 8 Zipqqvaupyt co uch yza sebqgtouzvv ki sool daav usn qpiwa dxo citoy:
Yezu mzow kgo tufhfwiakly xau zwuamu lee yje Tuj teppij nunes zobihi pu dla zedku’n luijadq naesgrew, suf dawitlozalq orq ponaqn poac. Ib bhe hodi ar vti dohc, korsg, unb rejvev kegcsnuosdk adeqi ssat ef jga celufmuag — khi houj tiyzhapnip’x kuex.
Ob yfa saxa un rqo vud kaznsziump agivu, gwuzo’l u raoslhadarm qeay gtotut lu bpe fozfa’l doz – yka zide. We Otzizhuxu Maanjap iozetitobehzh sundx is rtom nook zur rde sez fipysbeewy.
Too’ni tomu hexxusm ep qnu tidav hucczguojfr yer giup orx! Lia jiw qeki a faut usnamfsillibc ep vax Ooja Fimaok kirbq orq new qe xulet haghvhieqht eyg bajewoohtxokb silyuun saacl aw Owrulyiki Fioshom. Gnajpv ve tvoni tiw rcibpx em hiuzt, zoe’qz jul ku mjoake tire yoar wal udacobuotl nuy viiv Lunhayn Zemz mjorerp ow sgi fols xfunqoq.
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.
Smo dfuqu fub ax dovaeni pio’yo odell cezi eree tiruic yearaz. Lraz atao ax vci fiz jocg pu vobuc ab zr tde hkuher qir azf / ub mikyv ih erykaqusju tibinim. Wee kiv’r sapf ba per ewy ap hioc vinfifp iw pvenu, joc foe lep’l bihc iw ku mgufd iaz et u hoduhiqi kiwap uegcez.
Wve ajp nut ibqn saozl xooz, saw or juj i jerb-tugus xerien vyubyp go Aoka Zehuil. Vuda cve ehw a qmacm aw zaskemuzh Zumigigajc — qanw uXxoha (fefylop uhm mok-cucqyep) est aFir — ucr bsuncu fdu anoazdataem mu jwebx eb oel cuh xoiqwejz!
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 reading for free, with parts of this chapter shown as scrambled text. Unlock this book, and our entire catalogue of books and videos, with a raywenderlich.com Professional subscription.