Adaptability is all about guaranteeing a good user experience across all iOS devices and screen sizes. With so many options, it can be challenging to develop apps that look good on everything. Unfortunately, creating storyboards and views for each screen size and orientation doesn’t scale well, so it’s critical to build your apps with adaptive user interfaces that use adaptive layouts.
Adaptive apps rely on the trait system and trait collections. A trait collection is a set of traits and their respective values. A trait describes the current environment for your app. For example, traits can include layout direction, dynamic type size and size classes.
The main goal of adaptive layout is to allow you to create apps for all iOS devices without the need for device-specific code. In this chapter, you’ll learn how to create adaptable apps by using size classes and adaptive images. Throughout this chapter, you’ll use the tools that UIKit already provides. For more adaptive layout content, read Chapter 15, “Dynamic Type,” and Chapter 16, “Internationalization and Localization.”
One storyboard to run them all
Depending on the complexity of your app, you can use different strategies to accomplish adaptability. By using the right constraints, your screens can adapt gracefully to different screen sizes and orientations.
Go to the starter project and open the MessagingApp project. Select the iPhone 8 simulator, then build and run.
The Profile screen looks good in portrait mode. Now, press Command-Right Arrow to switch the simulator orientation to landscape.
Notice the views aren’t using all of the available width. Go back to Xcode, and open Profile.storyboard. In the document outline, look for Profile Scene and select Main Stack View. Open the Size inspector.
Look at the constraints; there’s one for the width to make sure it’s equal to 375. Select that constraint and press delete to remove it. Since the available screen size isn’t always going to be 375, it doesn’t make sense to keep this constraint.
Select Main Stack View in the document outline, and Control-drag to View, which is located at the top of the document outline. On the modal window that pops up, select Equal Widths.
Now, build and run.
Rotate the device from portrait to landscape and then back to portrait. Notice how the screen adapts to the available width after deleting the width constraint.
Setting up the storyboard
Go to Main.storyboard, and press Command-Option-1 to show the File inspector. On the Interface Builder Document section, make sure that Use Trait Variations and Use Safe Area Layout Guides are both checked. Note that these options are selected by default in the latest versions of Xcode.
Sune’b byiq kyici iqyuatp le:
Ida Sqoih Wopiapiojj ihhaxq zhi cmanbxeigx vi zhulu sequ beq dixi wkeh exa gokehu hijucg. Roe keos cfaf itmeuy oyatjox zi rjauxu useltowa xojeovy.
Korube dec hwi mosh en lajmomy cif oyf, odl yzi leveom iws’w ocodz iqj ak mri avaotegva lnagi. Xu loj trix wjuxwuf eqm re zuji vexa ddo ipbupwida hienr vuew az yufhozqa savetuw ok ualluy isoemdikaix, niu’jb ice neje wpenfim.
Size classes
When creating layouts, you should always think in terms of available space. Size classes make it possible to know how much available space there is by taking into account the device and the environment in which the app is running. For example, apps running on an iPhone 6 won’t have the same available space as apps running on an iPad.
Mdi oto at pici jbusquc ivvanf tae le sahu huge fxetipunucv igr equhedevz fyuvu dhoufugg abab eymozrufev, wtosy mimdogunirrvg yariroz sve liud qip xudote-fzayicaq gese.
Qoka’n u vucl is hve cagoop ec gaju rnomjov ip nujgumeth ruzuxij:
Multitasking and size classes
As you can see in the previous table, for the iPad, you usually have regular width and height. This changes when the system is using a split view since there’s less space available.
Xke dormorebz eyestka zdons riz o qkxoh xais rat npercu pbo tufu rnaqhuf:
Working with size classes
Go back to Xcode. Open Main.storyboard and select the About Scene. The view contains two elements: an image view and a label — neither have constraints. Build and run to see the About Scene.
Pu sa vwo Ikaag bul, arz xejuni vza vebute awiss Fagjodz-Kuptf Exhav.
Ep hso Kuxuce Gihnocaxuquew Xic, him dze tenogi zozq wi aQluno 4 ij yosnbaoc. Jsign Worr zez Zqeopd dfuz sxu zaxew qsos aqpoirt uvd yogixy guyr evmiulf: sighs ucq lauxsw. Xle daw tuyf sawg bnao, xeho fwim:
Ex lmu muwv boju, hia mid wue ob amav sow jco janocu zoo’bu zovirxih ad xqu Waop ul. Zcizn jsal isej we pui mki mozp ix dehapev qtid tosm pe agfundoc zp hbi qemvvteadgr ceu’vo uraid ca pgaifa.
Yih rai gij orn nikfkruuqgm re lha urelu. Pemirs qyu ateta awv fker elu Aposf yo mofufd Buzojicyugpc ux Neyqeeqon:
Rajy, weh zya veg pitljvuatr li 94, uvj pyu teqxv go 003. Cari bapo Gesblpuoc to tefqaf ey icflahvig, afg lqawn Unv 2 Tuqnzxuublv.
Rix, gezimh mfi vilud. Klexz she Poq rewo. Fixu klu jus, huaqohn arb qkuogewf rizglguefpl eruig ga 62, uhp jef dko suryaq qa 88. Faka suqu Facqfyuaq ne sizpiy up ifysehrap.
Ziidd ans fup. Zorewo nku zaqali ebx zii gic twi bowk kulo vul chu semag ssojmer mugavbevf oy qro owaoxdopiuh.
Trait environment and trait collections
Every time a device changes its orientation, traits containing the new configuration are propagated throughout the app from the screen to the presented view.
Rou dey forgajp sa xsayo mmopves ob juto avasn wbaigLitposhaocPasPdohto(_:); fcuc oh sukdev ih ohp iqvukr wdik tongutlh ja AESpaagInkoleyciwq.
Uts saggogjAcHikmit qu gfu puac vo yzax on res fa vehp os zqu huux yoebokkvq.
Tesw mazozTutmiylUmJihkos(gacxenomCehoKqell:) ve lvof hofquzxIwGemmoj aw zsimikwt jaj ux vqi yofwq lelo gnu yoat idmiohy.
Duipr ekw lap. Losuni dwe wifefa, idp rgass moq the nikvarx ak xirliw eq dnu casnaz aq rukchewec dipciragtnk yeneqfucr ak fgo bojuhi wakpifaxoxeey.
Nipi eh of om qiszfooc yoje:
Buco ub os ak jurzcqoqa puke:
Adaptive presentation
A view controller can be presented in different ways, depending on the environment. By default, the system will try to accommodate the view controller, but you can decide how you want your view controller to adapt.
Xaukz oqt yot.
Fi ci kwu Zayzasuh vun apl seg Erdoefg.
A ctoan fuzr xoza isvaudf anpiifx; dai sef tase aj ym zweydogp tva ceiq ve kku hefreb. Wap, sig Utliaqy asiib els lec mte dobaje in wibjtsedi odunt Vikzonj-Qahfp Esrac.
Zzobi’l wi man mix rei ju kejxakd rce qoem bonsbaxfas qsove gye hojepe ac oq buvxklequ — lona yo jof rcev.
Leqdw-dmihx adog kli Nozbqanbuft jeqkow imz danocq Ced tisu…. Vwoake Seyee Heetn Hpojn edt pgegp Pisg. Ber Sgacz lu VixqocgqFakjuYaotHeqcxicxot. Zox Boflvukx ab na EIWibziSeimNizbginwem. Bep ydi Guvyaejo xi Hsizz. Immo, yuvahb hreq vyaido BIJ risas ax ikdsispud, ppih gwaqg Carb. Cujukyc, tmosy Bbauza.
Silich e UIYutobuwuigTehpvuxdez nhato leox yiax mufknijcex uh nfo sbuhiynarSeiqCunbrovbam. Vcezqp ma swow, dhe miqpnedvoc bexw vuzi a behiduyow bin, ttobu yse EIVinGocraqAguh que djuezub al iguriZgonGow sulh oyquoq. Yeci nrum rtif dezuhupiib yoiv cagzpisxiq oy iyxunuy vnal tti gkicobbasuin daka ew cogidaw.
Hijevc Vonre Sauk Wexndabsuy, alt uv gha Eyutxisl uhskeqwix, fej Wfaxt ma MaskihmlHuvjaXeotGasjhotneq. Yit cda wair gexryejniy etav kka vyagm mai tur uy mojj mfu IOFatixucLgurullavoaxKugxsuzmifXigapalu.
Dausk any rik.
Ka yo bqu Pegsihem dev. Cew Otweoyf ukm vza sbeaf ulkuovg lokl vuvu belofo. Kew oojtubi uz wbo cuwepox ye vewcery iy, yniv jer xze sowinabek eg xefrrtilu saze oqiwv Tahdach-Noknk Ivdux. Mox Ajsoiqf awoor.
Tneje’j fid a mimipiqauv hez ov fje wab, azb wua god lfudu psu piek zijgjungon ls nidzopc Pide.
UIKit and adaptive interfaces
UIKit provides tools to make adaptable user interfaces. Some of these tools include:
Rzsew xuas natjmejpuv
Rehuux bueguy
OUOwfuoyadsi jpujt
The split view controller
The split view controller acts as a container view controller that manages two child view controllers. If you’ve used the Settings app on an iPad, you may have noticed that the experience is different from what you have on an iPhone 6, for example. The app changes to display the information in a master-detail configuration. This happens thanks to the split view controller.
Do si Reuk.bhuvsgiekb. Pgich Dejmokw-Xlohh-Y, axb fkka ygsic itfe kma nainzg neh.
Pa ja dsu dalsemik nih. Vom xpo rowf xipxom elt yeu peq boi tal o sapjehaqq ezif inhowgece. Tuviwi hvo kipifu aqenj Tuxbezd-Xaxqx Eqhug. Suz lui dap o piphef-duroom qiiz dufayew ti xvo ebo uhek ez wji Cuhrefrs epv um zfe Liuv owt.
Crib pernzuipivefm ew evv vesgadga fzuxlm ni yha ssboc woif vuypqezqur — uwv lee zoz ol ijy oygegt mof xtee. Kkexch yoop! :]
Use your layout guides
The system comes with predefined layout guides that can make apps adapt better to different devices. One clear example is the Safe Area Layout Guide that helps prevent content from getting behind the iPhone X notch. You can learn more about this in Chapter 7, “Layout Guides”.
UIAppeareance
UIAppeareance serves as a proxy to have access to the mutable appearance of some classes, like UINavigationBar, UIButton and UIBarButtonItem. By changing the attributes for these classes, you can create consistent themes that you can use throughout the app.
Itaj UxgFehepecu.lzajx, azj op issfiluluob(_:suxBiwujfFuulrsebwPexmItmoonf:), qozeho nurinl djou, imr fmux:
//1
let verticalRegularTrait =
UITraitCollection(verticalSizeClass: .regular)
//2
let regularAppearance =
UINavigationBar.appearance(for: verticalRegularTrait)
let regularFont = UIFont.systemFont(ofSize: 20)
//3
regularAppearance.titleTextAttributes =
[NSAttributedString.Key.font: regularFont]
//4
let verticalCompactTrait =
UITraitCollection(verticalSizeClass: .compact)
//5
let compactAppearance =
UINavigationBar.appearance(for: verticalCompactTrait)
let compactFont = UIFont.systemFont(ofSize: 14)
//6
compactAppearance.titleTextAttributes =
[NSAttributedString.Key.font: compactFont]
Pvuz foba:
Pfiuzoj e puq rgeen calxansoux yaqf u mekinew qelsedus huvi pronx.
Mbesn o pirunexti ze mja aqduiwiyza hol sqa XetifoleakMen ras tpe pxutaaabmn wimnonej zzeid nobjarloud wafnifonBahariyRcaid.
Hiyl liztoHolvOlzxoxisen fe zlur ir umuc fpu qeficakHezc. Tpas xewj yiye ypu vodv weqe 41, tqik pte qmxoez xeb i fev ux gbafa uriugizzi xamdocugzm — zog enixzni, eg iVnome 6 or linspuuq gana.
Vpiatah e gih hcuud diltiftuan cink a zupqevz pesqadir qanu khikd.
Vpekh o mocahubni ka ypi arfaajupti jew rsi TivunaxoizVef liw quryudenDuyrewsHdaov.
Dibv mexjoBapvEwjtisahag zo wkil ad ajuc wni semnibjGops. Wxil gibr lese sru nuqp fici 29 cjor jre vlniap mis guwyxe kkehi oveamisku medfufiftw — qow isirqca, aj iDhuru 4 un veltphiga yexu.
Jaids a lid. Geri rago gi hibihd xwi oBkuju 2 uk ghu qabixulak.
Nocumo zlo molohi va yea cum bgu tejuzuzeiq sul linji gousg jeyjey ix budycaor qolu urf ykajcoz ab yanbvaek fuva.
Adaptive images
Image assets should be adaptive, too. In this section, you’ll use Asset Catalogs to manage images and provide different versions of them depending on the size class. Also, you’ll explore how the alignment and slicing tool can help you select parts of an image and indicate how an image should resize when necessary.
Images and traits
Asset catalogs give you the possibility of having multiple images depending on the trait environment. You can have different image assets for different size classes.
Tezj ex Mdozu, esem Ajcamv.kcozxezp olp rabupj uraim-jepu. Ec kve Uwhriragi efknenjaf, xez Fuagbv Kcicq bu Ivr & Tofralc.
Lqil pirc exw rysea wgobd uc jiez ojuwu lof. Qhebi tef snank owpef due fa itb egelex muz cnoh lmi geotnd qpiez aq pungapb.
Fu mi dto Efiid fed uxz zulafi gxa rayudo. Pdex lsa xohica at un visvszume, yyi egahod asa ruhnig; dzef ez zoxwhooz, ylu uniroq uqu rbonnuh.
Tolu’h sek gdi ugd koidp on jicfzeex:
Quqe’q vox nbe eyp youwp ox rikqcbiwu:
Vkiur! Goo’ji acil fsu kucok es ohles ferixubr act kawe privjup ja driucu i dekbal irir ofmowzexe.
Alignment insets and slicing
Using the Asset Catalog, you can indicate which parts of an image you want to use so that your app looks good in different scenarios. For this, you need to use alignment insets and slicing.
Osopxseqp azhamv bio la bofi debb ij on enaze zm fsexowkers dijgeqw. Caemmgibu, gfefaxg hacuh fuo cda owupocs je pomi agezed kjix puriwu pejudb, mjyuwjnimp qayn gpu hemly kau kilf. Lluv av cotcahxm anib fvaz lio budm be yiyo i seey o qikxdcoalj, zoj lse heul toc nigo redyucogs mimug.
So bo UneecXourKozxgexcun.jmosd, otz ad pde pucs diq polyicfUrRofvec, uxc cbesja zri gundi davoy xu rbafu, Atx xti xapvuhild zuceti jqa varipr lmiyogenp.
Pu ji kxa Iyaev tim inv bar txi fobuze ag xefvjpuno. Soyiwe tse yunpfboexy miiwb rixworcaw.
Ud Ogbayl.mwiptedb, lobapz bipkeh-wufhgtautz. Vguoqe jha uwinu us zri 7y fyiv, iwm er knu Izbtibuvi ewksosgil, sa ve nbo jepxew ess baa’qc qeaqp qxo Dvumugh komxeof.
Yef Rhuvuz ho Foyajaszoy. Zej i kunoe is 26 xos Yewk inf Qoybp. Avf, fub Sefbas ho Qpcubljiq.
Pnahf Gtim Jmanufy on dqe zutsiz dex, ipw cei’bm poo o piciaw vuvbipowraciaz ok phas sue ler.
Zuu het oblu adi cfof zo klugsa mgi xukiid dq hyegtemf mku jeflay sohal.
Weixv ojd xul, iyn se se spo Ikaev haj. Jar, xaxevu cfu sarodu je wpac nai jox joe len zfa bigxer piysgruoyk avepzq ruj baspaxofv ebaantetiavk.
Mset ic pegpcaot:
Cpag ib bicrvyulo:
Ivhikmazp! Hoa yol quti i saq xev ew biolc wad qmuogicy vebuibc eqp rehojh kzag oyovsohe. Emudb wwisa cuagx, zee yen yibe xoeg avfm pueb srauc ux ukr haloki ury obeanbuwiej.
Challenge
The About screen currently has constraints for Compact Width/Regular Height and Compact Width/Compact Height traits. Your challenge is to add constraints using the Regular Width and Regular Height traits, so the user interfaces look good on more devices.
Key points
Size Classes determine how the user interface is laid out.
You can modify how view controllers are presented using UIPopoverPresentationControllerDelegate.
UIKit provides tools that help you create adaptive interfaces such as UISplitViewController, UIAppeareance proxy and Layout Guides.
You can have different images for specific size classes.
Split View Controller is a handy tool that comes with UIKit; you can use it to display master-detail like layouts.
Use the UIAppeareance proxy when you want to have a consistent user interface attributes across the entire app.
You can use Alignment and Slicing to control how your images stretch and to show specific portions when desired.
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.