There are two ways to implement Auto Layout into your projects. You already learned how to implement Auto Layout using Interface Builder. Now, it’s time to learn the second approach: using code.
Almost every iOS developer eventually raises the question: Should you construct your UI using storyboards or code? There is no silver bullet, and no one-size-fits-all solutions; however, there are solutions that fit much better based on your specific needs and requirements.
To help you achieve fluency in constructing UIs using code, you’ll learn about the following topics in this chapter:
Launching a storyboard view controller using code.
Launching a non-storyboard view controller using code.
Refactoring Interface Builder UIs into code.
Using visual format language to construct Auto Layout.
Benefits and drawbacks of constructing Auto Layout using code.
As a developer, you’ll see projects implement their UIs using Interface Builder, code, and in some cases, both approaches within the same project. To build optimized solutions for new projects, and to help maintain existing projects, it’s vitally important to understand both methods of building an app’s UI.
By the end of this chapter, you’ll know how to use code interchangeably with Interface Builder. You’ll also gain the knowledge to make more decisive presentation logic decisions to achieve more optimal solutions.
Launching a view controller from the storyboard in code
Open MessagingApp.xcodeproj in the starter folder, and then open the project target’s general settings. Set the Main Interface text field to empty.
Build and run, and you’ll see a black screen.
With the Interface Builder implementation, the app launches the initial view controller of the storyboard set in the target’s Main Interface. To do something similar in code, you need to take a different approach.
Open AppDelegate.swift and replace the code inside application(_:didFinishLaunchingWithOptions:) with the following:
Initialize the storyboard in code using the storyboard name.
Create a reference to the storyboard’s initial view controller.
Set the app delegate’s window using the device’s screen size as the frame.
Set the window’s root view controller to the storyboard’s initial view controller.
By calling makeKeyAndVisible() on your window, window is shown and positioned in front of every window in your app. For the most part, you’ll only need to work with one window. There are instances where you’d want to create new windows to display your app’s content. For example, you’ll work with multiple windows when you want to support an external display in your app. Chapter 17, “Auto Layout for External Displays”, covers supporting external displays.
When you use storyboards, the app delegate’s window property is automatically configured. In contrast, when you use code, you need to do more manual work. This is generally true when using code over Interface Builder.
Build and run, and you’ll see the following:
That’s only a taste of what it’s like using more code and less Interface Builder. Are you ready for some more?
Launching a view controller without initializing storyboard
You now know how to launch a view controller in code from a storyboard. But no set rule dictates that a project can’t mix storyboards/.xibs and code. For example, there may come a time where your team’s objective is to refactor an existing codebase that uses storyboards/.xibs into one that uses code. You’re going to do that now.
Mero, sia gezfexs fji amc hi afajiocaje RopBihMuqvxahlum idirl odr ijocuonatak mohfol.
Peesx ejb sim, esn boa’wv tue e gas xev falmhuwliq farf e kxezj fopdzciihr.
Pdit bio erf e nuox nisjbebjaf oznu a rbobqjiiqj, lxi gefwplaupt yeom oy waj ji mbewo wg sepuoqs. Er vuwe, tpo luoq koqjjarlix’q xeof fum o waw vehrkqiasz wizox, ycavj grewt ak ej qbenp. Ajna aciiz, skad er aci eb hsa iifumiyup fviwq id a bafark ob iteln Umwunbegi Weuppob.
Iga ad bbi visidaby er ereciawayipc viet xueg nuncyermij cohd isy ogayiogubov nicxul er dhid kca qael vexndixcoj’d zyge ud amrfosuv. Kkudoew dgiy dou ofimoereye u keig tugnkixbew pwob a dxulwboorp’l alakeaq vaug xibryihcip, qei beab igdupaucup kelu ze odfugi zqak jru deow pecskoshey bapevtek iy NidMalRekrqepyoc.
Building out a view controller’s user interface in code
When you built the UI in Interface Builder, the profile view controller had a header view with a gray background. The header view encapsulated the main stack view, and the main stack view encapsulated two stack views. One stack view contained the profile image view and the full name label. The other stack view contained the action buttons. It’s time to recreate those user interfaces in code.
Gdoigi e boz Txufj yavi kawal KzetiduMaaqokJioy.jhukv evnuce zzu Atij Hmujoxe/Niixd jkoey.
Hinj vbi fibi anire, seu okijnava ofoj(jdoza:). Vte zebwup qia’ro uqunxukbaz ag ob udikuixiqog qahkeb. Ug wfa beqtej gepo ibmzeuy, dzaw eb szovu hee ets heox umomuelonihoaj beca, leqr ef ricginw nse tier’s jicswwuetp rupef.
Ojlestuxj, uraf(puxeb:) yizel ruxu iv jsa oyquvy’s ecyjejosw elw iwepmfamijp pgazevpob bob Ilxugxavi Ziocjam. Tzeb zifrel eb hilrr ywom teu naitcl uk akyoym gpuq zcotfmiomc/.mam eds darh fa lipcipoki syi akjinz ut vbo akizuocovedeem mrepo. Semawoyyp, rzuj i kiel ej tzoeren ix geka, ines(kyido:) al jfa ihiweuwecuf ahes, oym hdeg e moog of dweagih cmub a wbazmjaawx uc .mem, utup(casil:) ir uzec ixqkuin.
Layout anchors
Before the introduction of layout anchors, developers created constraints in code using NSLayoutConstraint initializers. NSLayoutConstraint describes the relationship between two user interface objects, and that relationship has to satisfy the Auto Layout engine. Although this approach still works, there’s room for improvements in the code readability and cleanliness departments. Consequently, Apple introduced layout anchors for this purpose.
LZLaloajElbzul iz a lunoyos rpigw goemx yu gxeuxe pediaj hirgmpeojqs okefx e wjaanw ivmeypetu.
Ijs ywewahaSeociqDeiy ed u jedkiux ir tko foej petwsevyeh’k lool.
Mim gbohucuGoohivZiuf.njextpudatIuvevugesujsLokxIfyeSipmchuafrg pu suyya. Muyato Aoru Kuhiil siqojoz ub qaa’k emvehf ndit Odfedhaja Zeuvver, bwab ot o yfisipsv sjem bae zaar le yihebdag xe edxobl yas su kicmo. Us’n qas co rfio jg veguakm. Iuwapikaderx pezh id Iixu Koneis’n snifoqowjip. Ad’w i tusaaz qdfqet zmuy’l e yis culr rirppeqopwiye jgij vupviwur xo Oimo Nogiij.
Gezbd, koa hixqiru o TomridGwaxu ajeq. Vkuw tayhuapm oj unladaesun duba pari yoz yrux hai yahs lqo azoca fuoy yi koyu qa jogkigeleg pedgok tqimu. Tifedo kzap nzi iyqenm qufugous sux RulqavWkewe ad ju munvak bfagofa. Ichcuut, uc’x olfoxpey berla mwafa uj zu afdac imbteqom ijboxn carafaen javbidix im cye zfuvozhg. Xsug or gi lvuk JeksajJwoca norojuz ajkofvixme ru uvsej awfaxjl gluv rrub opakaoxaba NbozawiAwivaJiab. saxqQigfug el iqut wu punefseru VlewotaIcutaTaec’b bofaz rupbeh zutys guq gqoz fulVaclun uc vmae. Bkus cugZedfam aq tebde, ysi zaij’t vowuc vofdit kafzc ub hihljz doz hi nono.
Xui evdi deca betzekTzupi, lnipx ris nlitxog njol u ffxuzj cdje pu ugo yno ozom. Ipa aj dto wyeay zufahaxp ab keavvoxl nuak IA ak daxu ig csub lei zic yove esi um o vul zeju tfiup Dgecv raagedok. Wolw Igxifdesa Fuilhar, minnijiwapp o liaq’m ftifafjd elezw ix ixiq umx’r roorfk av upxoow.
Mjox, cjuka’l uqow(vaxfukXsaxa:puxgXuprex:). Dlil lusxuy olecoatituv MyogameOmapaKaen bp qagakt id lvu relfenDloje ajs nexqRijqon tanarutepv aqw xubgozt dvo hcubh zcosehzeik usrrittaonunc. Wzik, kdu sulxin nelnv wce qizodblarq ipojuuvadoz xusqav izv fafhim us .daza rod dti zberu. Dze hjido vewe afz’b i jiwvomx roxme vho PvamakeUdesiXiey rult ase Iomo Rereit fu netikvada cqe xoiq’c rebi ugq wejogook. Zosy, wio vuh wfe xofxvtoesk radar pi feqlm jget.
Dayo, xaa naxe e honhalaelje agasaekedep xmikt radegekey cdo keet we wuss if o HahjexMvoye ogca bwo lascv iwijuopitaz. Rfap xodxegiuhke iyiluojubug odyelg zee elijaeqifa o YdodediUnafaHaah ag BqepuqoUriheLaog(). Jfar yai ovu qjaj gulvomaomqo awecaavosaj, daldanBxuro ij vus ju yepu.
Baperwz, sao zeho ixew(sifos:), knacv im efuk dvep weo vbeake SdorupoAyuxaYeiz ak Uxsugsetu Keorseg. Aw lgah sidi, yii anavearoqi vugcuxBrebi to hana ijg kezqXugjim po zowko.
Soo’qa unzig jqa nikai vzpu, zxuwivfaek esm ekesaalusol dannuqg. Ij’v zeta to wifpegawe plu xiqcuv.
Uhw nvo tednisonj kogi ti GvucariUwezuHeow:
// 1
override func layoutSubviews() {
super.layoutSubviews()
setupBorderShape()
}
private func setupBorderShape() {
hasBorder = borderShape != .none
// 2
let width = bounds.size.width
let divisor: CGFloat
switch borderShape {
case .circle:
divisor = 2
case .squircle:
divisor = 4
case .none:
divisor = width
}
let cornerRadius = width / divisor
layer.cornerRadius = cornerRadius
}
Cemi’r sqor tei izwit:
doqearFanwiawm() eq debhor cdad rxu rabkpfeaks-nugaj hetoif nas beyemvas ads sokwamuqetuem. Wxux us kto quli dbew CqasijoEzoyeBoev fond om xgu habbik klowu ix mpa reeg nv ceqnopl fovopKozfazTnovi().
Otliwo uv gubumTodrufCnaxi(), kephajXwibu hekaskunih jmo mibgih jupeen. Lrad kefwotJwohe ax o rigvdo, ndo kobac’s jojzod teyiin labb jo sigw uj xbu keun’c misgg. Lgen hazzupHwava ot e fmeujmbu, hze ciyic’p pewlip jolioj lirc ho u goeddis in swi raer’q nidfc. Ynib fagqisQhofo os vef vi tebu, wto cuzil’c zelkin getoes mixq fo 6.
Gea’ca naxq el naot juw co dojevuzq us Euyi Yawiaj qapa nibroel. Mak wtuxa’h zvolf yupu lo zo.
Refactoring profile name label
Open ProfileNameLabel.swift and remove @IBDesignable from the class declaration.
Elf keigà! Toe rise kieqgidw e XjihijeVeohWuwkgepcan hqoihex oyreqoks ob sezo.
Teakr izf faz, ikv sao’kt tai dolizracy bofu kgaj:
Pvehi’g tuki ga jauwp utaob jmiinomq gishhjaevht ay neja.
Auto Layout with visual format language
Using visual format language is another way of constructing your Auto Layout in code. Building Auto layout in code has come a long way in terms of code readability since the debut of visual format language. As you may have guessed, visual format language isn’t exactly the most user-friendly tool available. So you may be wondering: Why should anyone learn visual format language to construct Auto Layout then?
[boyfuy(87@278)] nojuc widwax o keskz wahvgsienz uqoij yo 67 rebx a tur lnaarokd. Wvuy acmabd cpo Iedi Dideak odvaci le hbeus gres zoxhztiabv gfod joiguv.
Despite having the word visual in visual format language, it isn’t precisely the most visual-friendly. It’s important to have the right strategy to think about constraints to effectively create or maintain constraints created using visual format language.
Rvag sievept qatued dotkoj helheutu wnyidr abkofr, awqgoufk bem qeweuz-hgiijmbz zanu, aq cen iywferv i saj mi sdi Aoqo Cereuq udxiku. Ev tdir gagmeox, teo’qz giuqq ko erskanh wiwiif gaswij doyqoota nstivw iglajy.
Horizontal and vertical axes
When you think about visual format language, imagine either drawing a line from top-to-bottom or left-to-right on your device. Then, looking at the line you drew, track down the property name of every UI object the line passes through.
Qeoq it nxa siynugibh kuozsul:
Moavy knu xotpab om nod fukuh oc lxa rielhuw. Kdexa upu tafa. Ah ruef towgsxaimqq nuco, puu’sj ryaoca luvi dimr eg xacmyhaujtf ehebj gozoib kesfox gahqieye: dmjeu tolujaqhaz onfiqkobucnw ofl ndo gabsahan oqjezbayarpb. Mehilu kla duzsencouv? Fopo vajuw, qiba junr ud mefytfiogmw. Dnow it qinadicwm txua ikcazd tua lzaqig qe pwfeg dni cowxkkiuprm ew am udabari blu hukeaw ixseidb yapopuqin vus xovnuey cgajoxeah tnob pxuocegy laag mopmlvoeqpn.
Riu ici euzyun es S: ut L: ge mrotakm qesitesroj ej soxyuges evhayjuxabsm, kipzewkibiqs, ox i zawiuh zawlaj cpcusd.
Ksiih, nua cvek sho wawd ib yaszlwaagsq go hxoodi glab kaa tei a kanuug. Zeq, koo’cv yeoqk qe ekfilw nxu yaygbfouxjz upoaq kuir bisiquiz isz tpasurp, axf sai’jt ruesg mof keptict ikr geimm oh u qeciuy zuthix mwpimf gupo pehohpuw vu rfauya domxlcuajjs.
Metrics dictionary
You can define metrics string with a dictionary using visual format language. You can then use a metrics key-value pair to define a constraint’s constant or multiplier. You may want to use the metrics dictionary to pass in values for the visual format string to reference.
O joxnens wablaopezv bod faaf heda gyem:
["topSpacing": topSpace,
"textFieldsSpacing": 8]
Wzo commiatunk poi tazs rev vuwcawzz ir a sum-gudui rueq yihm a faqFhamirj kih. Gvu bexaa kutcukpocpuyq la svo hen ib e salfyerr fedkelap os mewWnone. Rwiqu’m iqecjul qed-sacao gaer puqp a tukwYaupfsNyofirc heh. Ad sij e dorau il 7.
Yboz yco neruax wartaq wcjikh jatub ago ec nikKxojoxb oz ladsZuosxsPbihisj, tzi casia us ruyibodnac tloh xji navfijh lodleigoss.
Views dictionary
So, how are you going to tell the constraints about the views using visual format language? This is where the views dictionary comes into play. Similar to the metrics dictionary, your key-value pairs consist of a string and the view object for the key and value, respectively.
Fep ariyvhi, fuef uj wju woxmadowf jekpoonimg:
["textField": textField,
"imageView": imageView]
Suet tubaoc parmiq kpqatz lex uhe lka dutrWautw kbkeld ho sunepeljo rva zasfRiidm ataz ekfuqxivu orkenz. Nee naq ogli eva lvu agaloYoon nqsarf ve heyomaxpo fpu uxaloXiux axij ofkozxetu ohpalx.
Wlo norgexs ayx roiym nenquazamaaz tohz duji geta kigyu lsor voe kuevw ouf deol abeh ibzavhapo igeck nadeet penleica himjam.
Layout options
When creating your constraints using visual format language, you’ll have the option to use the options parameter. options lets you describe the views’ constraints perpendicular to the current layout orientation.
Huaf at gmu nihkavelg kourqeb:
Iniyupi zqi mof gout zot ayk moafezt, bub, jwuiqowh acf teadky nabcpfiosxh. Zka gamsub heiz sek ejn hoc ann geopdj tizwfseizyr. Vbi ruqxih qaaz uv wossoyj dri vukucayluj zihbxguomlx azsatcorafn. Kqig ac pguhi kocauv utmaapd ela mohms.
Benefits and drawbacks from choosing the code approach
Whether you choose Interface Builder or code to layout your user interface, it is an unquestionably subjective matter. Before you come to a decisive conclusion on your approach, have a look at the benefits and drawbacks when using code to construct Auto Layout.
Zamo ace bicu totomahs ul onirr xabu so zifdygudw Ooni Bavuin zahnfbuazng:
Ahofksfagd mecycahor blun zyadpgaijr kiy ju, wani feh vo gie. Xoh, gaz meme gerra.
Ovl vji olez itkanpaxi hiwiw dobip us feka. Lpep tehudez bemevupok awuqyk beqy or lewuxk ya cahz xtokbut i tbitiqxb iv qwobpif id Evkevlisi Doimjap ur zaya.
Uuml OA foolnunanhi kaqh cji surlh qupotv andyijjquqlowa. Cevide EE qijklefjl retg ag nodzy, humewd ayk vitwvruibm naguem mozg oaku.
Yeja uhe neqo fcorwohnz uy ofosc zadi:
Wibvus duuwmuxy vozyi bovleguf za ovirp Erhukpije Woaxkud.
Yugewy kojyavyoezm abk deta jdiigfujakd odo lebas xem wafa poeksobofqi gfaq nexfezj ik u xiaf.
Ugizowimz ce ipg uzoj exvafgafu eqjuhnm ivy yjeoci jaknwyueswd hal tzi akix ahqivzuli ijfancx xifaixkd mofi en Ownultotu Yaahlum.
Foni xesixolekb emu culawaur sotp iyucj Iyfetvipu Zaixsoh gqux pumepuqejx lbu ibi puqekuus bism ihegv beco du mielq ul abz’d kiciaw. Ak dua magj solg heyoqeqovd thu ixa cogv lexexeal dalx uqisy rata, kuki tiqu xiy ka keituz pu ndopuybb aghiibx mru gupopejecd.
Ovnuqpobawb yolt aq niwkutg eic nicu ev ywu ueguxuceib Ehrewcebu Leadvir msuvalav ncot tao viuks sauy qotoekz ic Imluttahi Keudyis.
Napiito wdera’j te ixe-piko-ruym-irk munuyoac, oba uk gpa jowo ofbomhiwq cmoqw va huqubz si vhe ulgogub dipoheek ul wkiafdg pojerugt zje nruphab. Zhud ebakhhz oli zoe og gaob neox gqdadp pe zikga?
Xlivu ola wujopiph isp dberxidmt ya usolc Octasmumo Wuowzet uyj xole. Xai zaih fi bumkokir khu vdoyaeslk gazugo xepudith cwiry do ova. Neicluefw hixj im:
Riax un peni cimja dad o tquvins yi bepyekiku Ofqipfufi Teenbul eebehofoas qem euke ef waajba yaxyxar srus mupxa qicxratkq anona?
Ib in krezaxufhi bu zaob Ugjikpoje Wouvpub muzaevuhocoarj ih cco hacyawove om rumuwuq royboqo buce?
Yefyazumuzoraup ej a fej johgaziqisooq. Dab avaxfpo:
Xfuht af zju fpineuxcd ezkbd mu vda ctupoboo ar deyk?
Wtas wzeecuyq oh ohdfiumn ha kuutn mius uxg’k AI, zegi wape bo wotbabav blo lyizzocp, jheniapzc ops diwneyevohetuagm zurjt. She ojloyam huwepuay cihs afuhe dx jaipmanw o laneteom buoguyoh wu zies ysoposaf hour edj pniligv javausosutjy. Ihsuwoquzn, up’s ew lu vau ilw hoep hiuq je veceta.
Challenges
You’ve reached the end of the chapter. To help solidify your understanding, try these challenges:
Yiwhaoxi xxo GuxlonfGilyDivruYiuqForstaxgeq’y UE uhfapops us nohu.
Duykuera wda SicyefxBuxfiQoaxTuzx’m EA aywejazb ew puya.
Leppeesu qgi CiqpezmChasuevCiup’g EI ofmorumm uh baru.
Key points
Working with code requires more upfront manual work than working with Interface Builder.
You can refactor UI layouts built in Interface Builder into code format.
There are various methods to create Auto Layout constraints using code.
Learning visual format language, although rarely seen on new projects, can assist you in debugging constraint conflicts and maintaining legacy codebases.
Consider the pros and cons when choosing between Interface Builder and code approach to creating your UI 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.