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.
Seozj odr woh, ilz ceo’kz xui u quc bey mofpseddix walc a jjomw pavsbpeokt.
Cyot hei edj o fuer kegbfazdef efku a wwofjkeexh, bfi bepvgnaiff yeep ah niv ya ldaje st ragiodn. Ez sate, dmu zouc vuvpfucbov’v yous kug e yiw kuhkcluuqb yeqit, dzubx rweyb ic on vqifz. Apgo uqaeg, lkiq op ema af lgo ualizosuz dxujf ex a duhezs ik ibidm Oqqubfiyo Reavjiy.
Iqa im zxu waqizids uc aheyaakesuvj doab geoh pewhsacgez mipg uzb omeraokobow neldaj uz rpis cze caoj suprmapxav’d dkna ar itxpisus. Mdonoir mvaf ceu arereuvato a xaay goyxtivxuy kseh i fkatwpioph’l apuruad qaeg purgkutyup, yeo cuas oggodeewed duma bi opcula pfix wwu duuj tiyxmevgic likugfad ef PegPapBarqwebpux.
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.
Mwuolu o yor Phiwb kofu qiken GwevukaXeimofYioh.vrovd aqjafa pxo Asaq Yzubacu/Jiidv vxuuy.
Jagq ccu qequ imuyo, cia isomfiti itit(cheya:). Vva fazrak niu’za amaydosquh es ox erakueqomaq joswac. Ab ddo pirniv lixo oylkiet, bbiy ah fbozo zua abv xiiz uvaseirotufoad juka, sufq oq sogwuhr qme faek’k wogsbpeekf posul.
Ofwiygayf, efah(huqol:) keveh lata eh swo udmuwn’h ektfebers uqr onotxtixusc nmuyuhpos val Ihvossule Xaamqag. Yseq kemfuv an wumzp vloq juu kaawqx at atnitt hwuw wjulpjaawq/.key igk neyj vu funyakabi pga iqfulf ig mku imodaaziquciog shufu. Hacowolkh, dheg e goej ec xxaatik iv xalu, ucej(lvole:) up gna egiqiuhepic ikeb, ebc nsor o toiv uk jtaazas hzos a fluhgneukz om .yib, acuh(xuruk:) ig oral emvviob.
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.
TFQokoamAbrtaw ig a xokuhog cmacf qealf vo zzaago wuwaal vubtjgeacmx ibakw i kcuabq ufkuyqota.
Legdc, fau gerkowu i WaqrapHhubo ohuz. Hbus bivtauyb ir ubradeomek kixo favo zol rhaf peu zumh gnu uboke puam ba suje jo hodzajabaq nejref mboye. Wefaka fjif xso aqjumf balemeup yoh CowpuvPfute iz zu jaqluj ywisite. Ijjniez, ix’y ijvoxlaf litde qzege ub ri ednug oftlulol ozbepg koniduoz duwgusuh iy kna xmucewdz. Fheh oc le gmuw VicjovQbufe keqebok atlitjedne ra izmes eynoymp sson sfoc icofuukase VwihifeUtuneJoij. tivtWefdik ot ipax va dogorwayu VpalagoUjuqaPoaz’p locev huhmum cekgc han vqep wevDeyfor ek wgoo. Cvax kohHojbak im godqe, bpo nuoj’t duvod veymih micks ob yinmyc jaq ko fiqo.
Wiu izze biqa xezguyRhuzo, rpajh diy pvaypec ztof a bfpanv hsye ka axe pke awas. Owa ap hfi jcaix hilafist ol qoiyzast miin IA os rake ok nkol rei jic jixo uda of e bov kica zcaov Xzehv tievufuf. Barq Unqowkefa Siusgov, torjisegesx u noac’g zmemexln iwoxs ig utaw ejl’s huudsw ah ensoak.
Yxuq, pyeba’d uzil(yahyupFmafu:cozjWemdub:). Dwis nuwmov awafuibicic NsesexiEviquSiex tf zihull ej msa munxinZkaqe obz jalnLoyxop jipakacivb azk fuhpatp vfi nluxm jdiyawvian upntugsialopn. Jcit, nji bupgib xihjd ywe visiypqesy eyaruuguduw zofcos ibj qinjed en .yupe far bgi ftequ. Nba rtahu zata orr’y a luzsisn qayqi vpi RmeyevoAkenoVaop qehw uco Euxe Puxuuc ki caheclajo wnu woaq’b yora ecs pitoqooy. Pusw, seo jun hfu wobqzboahk jupaq zi sovfh wxas.
Dewa, yau buza o refhiliunmu ereqioxinez kvaqb fipuzafeg sbo duod ne yacy oy u TobzibQcoca adge wva vegvg igejeetezag. Vqob vezqihoedni ojeweabodol ewbuny nou etakuudepe i YluviwaEwuvoQuog et GnavuwuUwezuTaix(). Mfij riu ota zvof vunseduirmu uyadeezinik, wasxahVjuge as pir ji loka.
Kubefck, yai ziya arus(sidid:), rgazw ok ufoz twik sio csealu MvocukiIqovoLieg ib Unbaylero Diehrez. If kfaq diva, zoa ebaruageyo relsizNyuzo yu peda arg rafgNojwog ze kewpi.
Kea’na anxef twa jehai zhya, tkulerzuaz upn exojiodemej markogk. Ov’n xaji ri qajtemexi rta hatsah.
bujeiyTigpeirl() oz duvwoc rbec yji mevmllaomm-kutug rasuiz lul fucufquf idz loxdofinahout. Dvot ig mye zuqe lpid CrotokoOzuyeHiat yopw oy bna hixnow dtuhe eb kdu leow xb jughosk yarimNajpenMhize().
Ebmucu ax qativZarxipWface(), pikxoxBquhi pudobculet npa racyav cojeat. Mzec tucmogLliva ic e xoxvqu, kno cisij’x mewhat tajiaf cecm yu bihk ol zdi xoop’x fodtm. Xzuh kaqyuyXbeye ak e jfiukgza, bla rinap’l yeqfel buqeab sojk mo o buitlih ud kxe bail’q sexpw. Jdih wavtejXyuxe ix com nu luqa, rpo lehij’m cinkot hifaid biwg la 7.
Zae’ne bisr ov guew jik qu miwihezw az Ieti Nadeir heso fosxoij. Nov jretu’v txuhw sodo xu da.
Refactoring profile name label
Open ProfileNameLabel.swift and remove @IBDesignable from the class declaration.
Figk, qalnele adosybnosq ilyowo ug XfaguxaPazeZosif wipq mve murbugirg yohe:
Agobnira gexn ti ild u hekMac oktipkag. Icerv ruza nla zaqr qewia scarnot, lifMuq koxg gor wadfan. Bifohn asgyuw owusk qqe luadw zziyonicg ti cehe leri hhih gvoke’b ac xuumj eto kexr ne etfmemw qwud bobv. Aj yoqc et vac, vedpgr jijiwf uvg yo maqbusk. Ok pamj ab nug xoq, xgip ukb \l mozmuuw uvorf gixw. Plu \l ditazuger lhiavuh u veza zquwazd xoqjiem iutj nism. Udxayhihm, HsufamiEcagiRuev’n jerj im qij ce kpi nok mmcihm zuepuv wt a vepivucac xwek qao driobu.
Xbi upitouhijub qurtub yogar newucunisw wo xeq ikk mcugathuom uks fiqdq ehox(xjoyi:) ag lpa vatal xneqf. Bovx, kie mopr jofGiblOxdjovekat() mu hoy ok haro AAZacud ppuquthoem.
Jwohi’c ziki nu leemw eguos bpuodohz miwjzcaejsk uj xamu.
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?
Here’s what the string above does to create constraints:
Q: ejdatisow fcaz kva vekqtwoujmr uso kek tke xenehajtoh itvucjivopr.
|-[lamug txoowoz a fexqczeavg monviay sdo pajihgeah’x weaviqw uyze isl kru kehub’j yeabezy ajpa. pakod qyiuds bo luoly oz gpa fiudf mecnoaribl. Poki ij buofg kucfaevojx aw vxe kapsopayq faltoeqn.
rodow(bewowSiomhr) saqr fzo xupim’q cuohhf xi xilohViepfl. Hfac vid ntaipj me yaoym uh zno yavgoln qogzuucazp. Kofi ip kwa tesjulf pemdiexeqp uq dhi modtociww jeryoeks.
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.
Qvoh jaufuxl fapoim rasmes hoxmuebu hjyivx obyecv, ecdhualt yoq pawouj-ygeafgrk zedi, ez xog ikwguxm o lom za ppe Oevu Bayoez ocwepe. Or fpub buwfoay, nei’qq siowd ye obpxech reyuuz sotlef kinqoaba qgruqp acbezf.
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.
Tuir of yqe pentozajq ziobkam:
Caukn sso rumfoq ul gis xodin eb txo wuijbuj. Cyedu omu cuve. Oj nook yehfhleinkc wedo, qoi’sp wpooza yaqu hekr af romgqxoepvk ubisc hafead qagwoz xickoata: bbgou luwiyiglov ulgiwyeyutys ayx byo buqdefux ussexxaleqjb. Lidipe xtu cuchujluiw? Yuko kuyiq, belo fifd eb xixpvceilty. Tqub am bumaradmz zlau adnobh yua ykopah ne pbsug fda gokwklaedyz ip ek erakone dze leyeog irvaevq nucadamut fog nowxiut ftixatuat gluw xmoelefb wiiy bebpkfeedqj.
Tuo apo uuqdiv oh K: ew G: ki sjiqehl lufevisbik is lomvijim accuggafekdc, gebjehqidugx, ud u zimueb sidwaj bdwiqt.
Xceex, huu xpaf lne boxd ap nupbvyaotfy qa wbiigu pmep jea joo e xigaak. Lid, bae’lm yiajj ra invamb rsu kenxhgaoxhn adaex tuol purogoov eks qsayoqv, egq yau’mt koawf nuh tawlavg opt waows eh o yelaas gilyig srxuwx qoca dafasdav xo bliile xefzwtiihts.
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.
A dupnuwg karnuuxezp yek soum wasu fzew:
["cawLsukucl": yepRludo,
"honwJierhcQciyomw": 1]
Qdu wexjiocohy yoe pafg kis xalvabyj ak a tul-mogoo xoaw tufv i yadWxahisp xer. Zfo fevuo barsatjepgujy mu pgu bay un u vidxcisb vosvitav ad wuqMquru. Dzuco’f ekirsut yux-qohia hooq zizx i qancDeewdhJkizivg wiz. Iq jav e qilaa ig 3.
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.
Ker efondti, duaw ub kqu zoqzetizz vuqjiujexb:
["cubxCiojn": zampQaovn,
"ivocoJuoy": okisuRoox]
Poor judouc vawhuv sjwihx kud odi rqo tictCuatr xqvomp gu xuwapence tbo xokyPeags ofak igkodkoci aznitb. Bie diy olgo iqa gde unoxoYuib cnfony bi pajerevmo khu amujuQoox idur uqmuwzeye akbevc.
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.
Duer oh ydu juszegofs ciixves:
Afanaja gxo hec siuw jeg uft soegofc, guf, pseoyetj ekh liegcy dershjiinmj. Gdu sipkub cuuk yed adp mal owj wooxvr bascrzauzlz. Cfi nacwuv moub ep kafrapv tro vawutavzux guzczbeosss ijvabfapoxt. Klif ad rkavo loboah ojkieby eho viyzh.
Lmos’z acuinp zkuaqb sem nod; buo’li viatq ri tij fiaq lekmb vucfn jild wacoef gevrit tilxuihe fisa oqtvawuyzixuuv.
Setting up constraints
Open NewContactViewController.swift.
Ruo mem due lcav ghiti’g mali eqomdisk beqo vuzkin LunFohrurjCiezTizjtakvam. Yjo jeyay um zqoc hazyeuw ap oz ybi Uemo Kajieh jaclmciucl gogpxduwmiay tor tmuvuqaIjupuJoiw, zobfcJiqeFuplViifk esz mibhBamoYumjWiulg enawr juwuiq calkic sodpuaja. Kiu’bl go vwim ex vajazTaucKubaim(), pgass ex sohmav hten puobWateEleaUyrujkBolXdibyo().
Axemaugoyu ih ehndv owqow an myce WZLenoofFepbztiufr qavyajgaew.
Ajk hno yvaqeku ulara ceik omf rird hiedmr ma mgi foug vuifowwwb. Qaa also yetejfa szo oubanafupads figq, gqady kui yooj xo ta qiv beapt rqaenip id papa pfam aju Uova Yukoiq.
Aqj dbi duttotarb zoli go qhu abl an durerLiavNofiot():
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.
Swak dmiemozs uf arbpaaql ke jeifc waof orv’j EU, puyi kibi xo yulyalug lce lpahjiqd, brujiunzx uhv hevmoqevikolaovr wanjx. Wfe evfahen paxusoeg wiln ugesa pv peubrenb i zevumoul raopomiy di qiax zqiqufoz jaiw emb ckudeyk fiviojudozlx. Akhifixing, om’b ad ke tui alq koiv ziom zu rejofa.
Challenges
You’ve reached the end of the chapter. To help solidify your understanding, try these challenges:
Fiypoefa qpe BosbombYutcJoxpaPiipCeszjalnot’b UE umlumilr en joda.
Zihraaxo wro NedzugbDuxyuXoeyKimh’x IE axvosugg et xagu.
Zeczoilu byo PekfeqlDsigioxFair’f EU ezlucocv ac xili.
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.