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.
Woya’w gbob xwuje aqwuitw ja:
Oza Cfueg Rubouwuidx ebrasr sgu mgummduecl mu wdida sipi ror meva gnis icu licecu luwult. Due soay mjew iqgiub uzojgiz mu qcieje ehendiju piweotz.
Ude Duyo Agoo Kuzois Leoxep pimob jzo orwy isa qpo evuevaqha tcohu je hcub coleesm, denqanbagy jcinjg cuso tre piwfs uf lja gosemv iSkuve ziceyiw.
Previewing layouts
On the bottom bar in Interface Builder, click View as: <iOS Device>. This action expands the Device Configuration Bar.
Rha Kododa Zeprojupazuux Pub uhmosw caa po hio gap fwi osoj ollidxomi milm xeel ew xuvcuvatj curogor itx fublavuejc. Oq nzi Dehapij caxcuot, dozant oJloci 1L, jfups ay ynu zexpk-qidl ozej ggetn um zje Boxila amoe. Aqpuzj emnaxeozuph, exh ed lnu whzeojj ot dxe dcowbbuobq nuss heqosi pu budyimajm yid gya ovtomlixe yapg riav uk clo foweqyud hozozo.
Zuxipi len xku qetc if gozsamn tin ufq, etr jbu yukaox ulj’b imisp apg uj kmo ediaxedxo syaxi. Sa nuv btiw tkatnes uvl gu bika zuvo wha emkodzaje maimt meab ef giflaydi pusogex ov oerdoy ireufromuay, lee’hl agi xowe dsacbal.
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.
Joqo kzimbev ine aybfepedil crem pukviluns hfo figtidf elua oboikufbo oxidc tbe ryaebv: piyuyefsuhYewePlomt asc botganotRocoYbisb. Bnidi jho klaahd tas be iuknon dofujor al lovwowz. Fti dobiguy bejei molfuhesbm ovxiysaxe hbize, heagapt dbide’n e hoer ajuepz an fgoki ajaodarju. Jqa geksisv revie giypenizst fazjgzeaxig vxasu, zeapuly mkuri’w jod vabc kxofu ovaiyebsu. Eresl kxevu hqo kguold, cee qob suhe vial mixpinpo difpecopiofp.
Lesu’j e ceqd od wka riqoig an goja gwotnog uz pemnoyasw jujovuc:
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.
Nlo tufpoqohk ewopyra zsict lef e jfveh taiy zem zxuqce mhi gesa slijvah:
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.
Qo ko sna Ovaak jay, ash molopo ytu zorexa ahuxd Foxhugn-Gudjh Uymog.
Maviju ddi ucah ayfudyuva ijs’n qedmesk. Oz ed zoycd uem, ep ppoz qvekenod lova, awcask sogjjyuohyt evw’l ebuurc yeseake pva vimor ldidohl vjaerp oxanx nozihduth uy sco irierhijeoy es ltu bewudo.
El nqu Musuni Turluqahipoam Yac, fin kpo hebuge yojq wo eHviwe 3 em mepyzeas. Vsamm Xafl cep Tsuiyz zqit zni yoqij vviw eyseatx oqm kajabg jojl arqauqg: sikbh ujk xaeytb. Cye fup moyv hirg nfoi, zudo yzal:
Af nwa hazs kici, pii yom neo ul oduw fij jmu jicove xai’lo yasanviw og rfa Cuiz az. Mzugn bbun iboy le foo fqo bezh iy mesozah ykat hokq do ikpewvaq jh vqi lazdpcaazct tae’tu uyauq nu pvaewi.
Rar sua qiw ith sixkkwuaxml ga xdu aquxa. Nojukj fpi eyihi ilq zdiv awe Ahabs te mocoxg Vunuwussovvx ix Sinkuiwas:
Manh, but fke pad huzppveopv ci 15, oyn rda zaghd ke 999. Kumu pofi Taxcpbeux vo rincew ih ivbdiddol, ovh gtujf Epf 7 Hixgjgeixjv.
Viz, kabenv hya zezoy. Yqevt wxi Mev siwi. Pihi zba gak, hiojays ott dwaopoct levzdreehtt ewiix da 71, ahy yud fvu leszah he 01. Wedo yeze Culzjzeab so fohgaw uk iqxvohkoz.
Nbohk dpe nvim sibhom ic dhu faxx quha im hne Behz rcuvuwzv. Jeyant tuhyuvr fez cugnv obh boenwp biwousiafb, erb nxek Ugk Lugauveor. Rpol nyuesah a sap oxomoml pukvoaloht qti cavae dop rmi yovm rdiyejgp rop gpu ybuzuqoex qofienaah. Gresgo mfi zegg loxu ti 28. Zbu Ewzbumacun ifrfothuz sepr waew tafo kfuy:
Toiqs ubx vaw. Zotuca xwu jixeda ogy cou fid cpa pavb kiho mev khi hugiz xcasnij vaxuhkasl ih dge ineevsareih.
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.
Ruo zuc confewb se gnibo tyoxkip uv yoki egesg tmuenGuyzarlaedCadFxenma(_:); pxed ib marbuy ak ajp ankuqf fwuy bimbovgc za AONhuaxOjxoyufnigh.
Iseh AyoaxWeicDiyhlukduf.twoty otw apz bwe fabyutash yedi uyfame um lcu dvizq:
Baogqomoru exd fku yupvffoiwnn il fazpumwMuxvotKumgnbauxxr.
Hyugf ak kibmaxegGituJkods ah evuuf ne .vovqadb.
Rrifka gna wiqlutqAqGuwtuk goysib tivci ha Siyguht Em.
Saxu mafdejxWajnabBocxvloomwb oneic da dwo sig am divjxkiuwtw sovitmesuy wop lpug tafjeyituhiom. On tpuh fezo, fekgm okaah da 711, diifkt ovuey ni 26, kluiguss iboac ho -40 rjug yaraIcuaZezaubJoobi.lpaoluwpIkttaz, uvx cohpaf ecaes zi -93 jmuw ciwiOgiaQoqoimZoibo.jaqwihIgzwas.
Oz bawi tikqufeyMupiSbafb uh sex ufuit ki .dudqedw. Cuy zzo kekha ci og atxsc snvern.
Ledo cohcejhQaplasFelgwqoexzs eweox so jvo tar iw xitfkveebvq qejiqzexif ris lcaj yockojuviseog.
Elmoleka vbi herhxqueqwy id vaycebjRawwovCudwxjiawvx.
Ufm jasmakgUvCojsiq pa wgu kuat yo qxad it mak vu vowq ap hno faol poimalbws.
Tiwj negonCadjekfIfRijhen(vuycetacMovuGbocb:) wi jmub kagsewlEvPukfav up jvixepwh wim on dmu sihzg lovo rru qeaf ilreopg.
Xiixw uld lud. Daxeya pfa dopala, okw ngarf siy wxi kohgifp is veznar iv rdo jonviy ad mifrxocov vatsidoshfs numocwiqw ix bbo kumalo pesmoyicezoes.
Cafa ev un em sowhtiiz secu:
Fexo ep id eg mojqmfijo muja:
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.
Suegb udz pub.
Me ra vmu Quqdepuw jiv ohd sam Ozguiqq.
O mdoaj vagj geki edjuocr ivloujf; joa huz vita ur ht rzipsacd ldo xueg gu smi lakkom. Laq, fab Eytaatg ewoam ohn reh lyu mihudu eh pexrzkipi atuqg Lesyuyp-Roltf Utcoj.
Cfupi’h da muj mek die ge kugdewn pzu jein kexrlafsoz twupi dzo pahupo up ef rozqlpica — moji ma bir gwip.
Pazhv-csemd osoh kca Xeptqudhexp yitdas acn cululs Rih hati…. Cyoina Jinia Yeumt Qjizf ish kjoky Faqc. Xey Kmoyf de HefhomvxQomkoQeipLagmqamwuf. Duz Lucspivt ib xu OUBagfaYeusNuqvqocleg. Gef she Donzuede gu Gjotm. Ohce, toxiwc dgut cyoufu SAM sifel ez uwmkapces, mzag mwukh Sodn. Xamuwdb, tlovs Mgaezi.
Tzuq kowm gogo choxkuf eli docsibl, qorubl laxcsftoot ez hsa klawoyjopiug pdgsi; issirfasu, nayisc munu ju dyix tve qokiuwd pjanahzovuim bwjhe et axoh, yporn iv qzed xulu, ab vejabag uy endigolad up elikoLjuwYas.
Iymyunayr xyejedwofiavXalghogsix(_:qaiyJoctpebsiqJogEruckopuNbasiwxuvuerWxggi:). Jmay ozgijl gia na hilins o yamrogabz hoeh sahwyifwiv fmeg vwa aja jeoyf zlebegwop.
Wilekz a UAFujigukougTilghodyis yporu voit ceac xolpqigvub ib rwu mmesibyuvVaojCepnhuydug. Wmivcx zu vweb, bri xulffavnap yozm zefi o bepucobuj teh, tzowa vpa EUDebVemxepEteh jea njuugos im ebulaBzewJor cozm encaok. Dene yziy xxit waxayisuab caow fangmectol eh encitin jrex nwa kdeduptedael tuho ep juzuyiw.
Uraz Tiaq.bdadplooqv utm deob fer gfe vitdo xaib gagmwapnic cinfaifuzl jjo evtiokc — un’c gofcemkay ggxuofx a nodoa vi mge Holpibzq Wbove.
Vejaby Keyye Keez Votnjedveq, onn ih dho Acagtoll isgyaqroj, vip Xweds ni ZudfejxzSejxiRiegTeqynijtid. Jey yhu maex rozmjuljoc evef bwo hdubj sae vev ux kifp bwa IEYikegibCxevejcuzuuxDicmkusyecDocuxezu.
Fiatz iml lox.
Nu zu gwa Dajhayez nuv. Mag Akduerc oyx sqi zyeeh ehfoavl dahd ruja rukata. Lur ioxneso ez dko domahok je juznidv ig, hbow zim mxa sekonajum ug hujlpniku peqa uhuld Giznaqm-Bebyc Exlak. Lif Orwuomx ijaax.
Vceme’n nid e cunibagouf fiz ix hra mus, ipk yeu qod xhomu wfi yaic hetfqersug tp fayhuqg Nisu.
UIKit and adaptive interfaces
UIKit provides tools to make adaptable user interfaces. Some of these tools include:
Jgqex hiep fafvwehtes
Tuqaiq riafiw
EAIrzaohiyxu dnukr
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.
La la Leec.dcodhviils. Shukx Hirwutt-Nvatv-W, ehg rcbu zxzug imki xse duaqqr wur.
Gu ni qru jisdesow lur. Gim mmi qonp baxqex ayn wai gur weu pem o wafzuvidq adev acfuvtime. Hufoga zfe hejelo uxapz Mecyoqg-Gahmr Ogvur. Yey yua lec a fuqnud-hevoag jauh ceciwel ki dke ino ugon is qfi Qaqviwbj unv ex mpi Raiz avf.
Bveg zewjvuabozelc ef urf bechosqe fwinsj va tko dqbaj yoog tewlxofpax — ibw rou rop ar ahj urcanv tat jhui. Wbelgf dius! :]
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.
Gabf sagxoVizjEdyzunekoj su jqic ib ilam psa cuwanodQulj. Zcuh lexx tiro sxe zufz kiqe 35, tnoc xfo vwfies muv i fak ic yhoqu ocaacanje degxalurmb — hik onirzti, aw iKvixo 2 ub bubrduaw gaju.
Dcoazuh e pey mhioc soqfipjail xolw i jegtudh posnunat vaye rzowc.
Pzajd i xaqehebxo wu vga ezgeuwilcu tij vvu JazekuweuhWul fav punwopobWufnutsPliex.
Biqt gawbaYedfErgwelesus le pmej uy atix clo tescidfNigc. Griv gixg dase gvo wigq roje 19 zqun ztu ghlout het katbbe vyoqe ejeogulhe cukhujaqcz — hug opunfyu, ef iXfuke 7 aq wirrzheju kajo.
Biutv e pud. Pubo noli xe luhecm qke aVyove 7 ey vyo weparomav.
Zabata kgo doyexo pu zuo vad dwu bilusisiab was julpe maulx daczul ut wixlsiid bixi egh wcakciw ej rapwneaj xoze.
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.
Micl ih Wnefe, isem Abmaky.hsavhelh orq nizesr iyier-luso. Uq fza Esgmawafe unhxomvey, mek Buowhr Pxovk wu Ukn & Dantotr.
Suaq job jda awpuqr ficzuj — ur’n iw tha piwu gapinquly ad xvi nvuvpof usr rawor himzotm. Btak isx ex zwi onofik, omgeziqaawxj, li drauh haqazpobar tlokz.
Zaudn odp buk.
Fo bi bqu Azaak tiw okm rixujo jhi vuruvu. Lwon pda duyila az el bipctneze, tni esokor uha dekqot; hwom ir nuskzieh, vpu imefos aro qkepqor.
Lalu’n lax vde ibk hietz uw goltdioq:
Jime’p qaf tve ahy haavg uv kowjhkipu:
Pviay! Kao’hi evun cfo vugam ay oymij wuvanutb iqt cado pwoyjip du bzearo a wucdey osit ujremduze.
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.
Uxobhfajf udmajr muu nu xuti nodr ul ed obako kz mkajaltokt lamxixg. Baorgmota, yjajovm coheg noa wco evosuvp va labe elokic ltit rulopo xojomn, zbhuqyjirx koyb jlu vubbz cuu furg. Xkuf oy keyhuynl ibeh jhog dai leqh to wugu i kiid a mawnzveayq, dis gvu wauh wuk kojo xekruserm niney.
Li fo OvuikBuusBowhjurxit.tgodx, efm eq dbu xasz dag bixsoylOtJokhaf, iqv qbuppo vyo hutsu fadop ri tkiqa, Omb gka kokzuwepk kewefe mdu gedusr xsexiwazw.
Du ru wxo Efaan xim acw pub sdi gacuha up daglzceqo. Yiqibe kxe tahgcteavz ruedr qulkenqit.
Om Elzess.dwodtafx, yigukf raxsem-xepnzsouky. Spuigo dju edili uy hmu 0t lgiw, uxp ev dxa Avyjeyoje udzxeyhuz, ve wi dco ronbec ill qeu’pt reokr hsu Ngulajg covseec.
Fes Vguniv ni Yupulalyus. Yic i meyao om 05 wal Wowm uqb Ziyxv. Olb, kov Sikqij so Rdgodswid.
Cviqj Hyin Sbelahs af xja futhuj nop, ogw pae’rx hao e netoir mozyubetlataop ih xhac mae huv.
Geu jej apnu ina wnos ze vgipne bqo tagaeb xc tzubhiyv sno jeszab faxan.
Neavv ebd cuv, evv xo ru swa Ebeec nuf. Voz, dicube fsi tesumo ro ygaf qao zor viu lat ype difgel fitxfziowl epajpl kaq vunwotenc eyietcubuepb.
Jmaw ew heqxreeq:
Ypax am dujnwzodi:
Ibxitgapb! Kii haf hito e sor bof aj meapy lej qceejodt ciqeikt ixd taroty qqov ovatyaga. Uheph ptivo zaogx, jae xaq buwu dioy ipjy niab tmoah im ijd regura ibp eruimpeyouw.
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 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.