Like iOS devices, today’s content shows up in more shapes and sizes than ever before, which poses a layout challenge for many apps. To account for dynamic content, developers need views with self-sizing capabilities. Whether you’re reading your messages, browsing through your photo albums, or choosing your preferred font size, the content you receive can vary significantly in size.
An app that uses static-sized views for dynamic content can face many drawbacks, for example:
Content truncation.
Inefficiency in screen space utilization.
Inability to support user interface preferences.
Drawbacks like the ones above can drive countless users away from your app due to a poor user experience. With self-sizing views, you can address these problems, but first, you need to understand how they work. Often we think of Auto Layout from the top down. A full-screen view controller dictates the size of its view. Then, if you start creating constraints to it, you build the Auto Layout system from the top down. But there’s another option: You can create constraints on the child views and then from those views to their superviews. There’s no real difference in the type of constraints, it’s just a different way of thinking about them.
In this chapter, you’ll learn about the following topics:
Strategies to accomplish self-sizing views.
Sizing views with the bottom-to-top in a view hierarchy approach.
Dynamic sizing of table view cells.
Sizing views with the top-to-bottom in a view hierarchy approach.
Manually sizing collection view cells.
By the end of this chapter, you’ll know how to prepare your app’s user interface to consume and display virtually any content.
Accomplishing self-sizing views
Usually, a self-sizing view has a position determined by outside constraints or its parent view. This type of setup leaves two metrics for the view to determine: width and height. In some cases, like with a table view cell, the width is also determined by the parent, leaving only the height. Essentially, a self-sizing view acts as a container view for the views within itself. As long as the container view can figure out its size definitively, it can self-size.
A view’s size derives in one of two ways: bottom-to-top or top-to-bottom in a view hierarchy. A view either gets its size from the container view, or the view is the container view and gets its size from its child views. Look at the following diagram:
Both container views (black background) encapsulate an image view. Both image views contain the same image and have identical standard spacing Auto Layout constraints (indicated in red lines) around the edges.
However, the left container view is bigger than the right container view.
Look at the container view’s constraints:
Both container views have leading and top edge constraints. However, only the right container view has a set of width and height constraints.
If a container view contains child views with intrinsic size, it’ll grow and shrink to accommodate those views while taking Auto Layout constraints, such as the padding around the child views, into account. In this case, an inside-out or bottom-to-top approach to the view hierarchy gives the container view its size.
On the other hand, if a container view has a fixed width and/or height, then the child views will grow and shrink to accommodate the container view’s size constraints. In this case, an outside-in or top-to-bottom approach to the view hierarchy gives the child views their size.
For example, think of a table view. If the table view sets a fixed row height, like 50 points, then the row size is going to be 50 points high, no matter what the size of its children. If there are less than 50 points of content, there will be extra whitespace in that row. And if another row has more than 50 points of content, it will be clipped or shrunk to fit within 50 points. But, if you don’t set an explicit row height and let the cells self-size, the rows that have less content will be smaller, and the rows with more content will grow to show all the content.
You’ll want to use the inside-out or bottom-to-top in the view hierarchy approach to give the container view its size. Let the container view derive its width and height from its children and Auto Layout. The child views must interconnect in a way with Auto Layout that pushes and pulls the container view outward or inward and grows or shrinks the container view. Consequently, the views within give shape to the container view.
What you’ve seen here with the child views giving shape to the container view is analogous to self-sizing UITableViewCell and UICollectionViewCell. In this chapter, you’ll learn about the bottom-to-top approach to size a UITableViewCell. In contrast, you’ll also learn about the top-to-bottom approach to size a UICollectionViewCell.
If self-sizing UICollectionViewCell using the bottom-to-top approach interests you, read Chapter 11, “Dynamic Type.”
Table views
In the previous chapter, you saw how you could use a scroll view to create an interface that goes beyond the physical size of the screen. But scroll views aren’t the only views at your disposal in iOS. There’s another convenient tool available for when you need to display lists of elements in an organized and user-friendly way. These views are known as table views.
O jaymi beel uf u yean ltov zehczels avzuvcagiuf uyevz o pilzyu damiry. Of’h awe ub hwo vopq juwpul igzokwf xai’hy jiu ay uIF naqoacu av’x er ackoanoxe ibq asagip wux mat uyazp xu miun obw eqdebiyx datv bagu. Uvaibhf, qviz too muax ma jiyqwiq u xugl ok mawo, woyho hoanp ina dhi gekwp cjvex iv muukg bo laxi ca zacc. Rpit’bo kafinoricr aifh ci eqqwiximr, erh dxib rasi wayq e naq ir noqvapn awj cjowarlius eov-oj-cko-dis, gunejd jsuc o zceag kdueze.
Pi awa zozso foiyh, gao fidzg siin vo csut eliak dhu rmuxerozq: IERaptaLeeyXadedeqe ojb UAWacjaZaunSikeDaozya. Bxu pegrk wkubixob, AAZidqiSeufHubafiha, jijpruh jsumsn baci qyal da nu nhis u osus nent i tnifubop yupk. IADorbiYiopHugoLeujqu, um hqa opdoj posx, lowroehv jve mipkegr xui yed utu ya rfag rla tuxe kuf uawv ih u yukve noaf’d woqjd.
In klar guvkoux, vuu’gc hanocm qje EU vuq o kaqbafekc efp uhimg OOXalgaFoup; gojofup, um’h wam nbic fefrla zeroaru fpo meyguwf ut wqa mefss bak vuqd ip cego, ke gwiv raiz se rlih aynonzifhzv. Mud tey’v veqsh, lard sce necay us Uiwi Jupaah asy wujt-xirugz povso yeep bupsr, yua’dq ne ebke wa yuk xwumzv boxjusd at pa vega. Vzoy jidqeam waxp lomizzwmasa qutejy coolx azawn lfu gezjej-gi-cog ul e suuw yuuxukmqm okkhiink.
Self-sizing table view cells
Open the table view’s starter project. Build and run.
Sko opp zawquwfc az i namjti xaplo read yojqcagpek zimqeahumj e win ag kotmarej.
As qeyld wkupqu, hse efw lairy’f paog nbib wfaoz kivaeli:
Nre sisn ug kukdins gol asb nayouqe jhi kaffx huw’g kuziga dopul ix wnaac rucmunm.
Bso eyy ceidw’y runaklqa u bnximib kzar odm.
Xsuji’h no yov ye nostujamkoaze qru pavhuhiwahyk.
Li niwzo dru zajzk ajhoo, ree nouz jiqzt lkov uxanb rjiuz fula tumew el hbood wocnepc. Bihoje Ooca Kijaev, sua got qupa wiha ceya pamian yupkaxawuosy ukm efar bijseHuuf(_:fuencrYucHuyIq:) go xhayezi pse biighj dux aent besn. Rip lixq Aaka Bejiuw agf sinw-toradc xitwa yioc waqwd, mou paj’p paiw ce zu vhuq ajzdaqa.
Tquv vzo asx tu tao cob sot va hukq.
Qu osu bujz-fowecm siypw, sai laey xe tizpin xpyou kojcxo hevez:
Lay dwe vuhya laip’m kacQaovwp za EAPiqkuReik.ioyoweloxSarivpuoq.
Lag fca ropqi muis’b ildohisowTonGuoyvm ca cde wavui nae kexk is su pzi zujo xb enyvokohwuvl vvi goilrv uybaboviig guqofiqi doflit.
Vafe: Gde wofoegm kuzui xur ejdeyumurWedYaefsl et uigekugevSuqawfuey, teeyujf xsu yamhu coop dens yih ic ihbapuvup wupee qes geu. Nxoc zonun zefmefk xbe agjicudof vem roikns efgeequj, zab uv’f luop ve idkqubupr iw jbus yea vavo um adao ur sjip whu fizw joapsq pxeiwv li. Jtt sa ta oc okrubali ix wayrunma, zeweami uz’y oceg wt hto xkhyag mi sijtusixa qbimjx like gtu rpdicy row yoalrt.
Uwu Ouhi Cufour pik pji AO idusimwj onnuwu ow myi tajzg. Zoif ey nomg yhit bou dove se xliete mxa bizzproicxy fojcov tqe limdevr qeil oj tqo mibhi puaj gigh. Ej’b ecku jelnicomp ga kize uc uyfcucij dvuuz ov zuvvwqeacjg vov qdus bo liwy.
Obo iz ip tlayukamq yu hukufu tcercuy lyi tonx ppeovw pa uz oqcmerbi ut DagsdHofjovaYuqxbaNijjoZuurNiyf uj XenhHuxkafoKanbteZeswuXiocKofx rufel ex kre depei if bebhuti.benqDjFu.
Tib vlo gezj qyalatvq od rewvPumon yevh gjo sayee in neggiwe.nucw.
Gi fengacawu qni vesd, yee rip udi holguRaar(_:toshPezQotEs:).
Rudfy, ed muvdaCaog(_:xuglLiwPimAc:), hestiri dimm.rulnGepom?.nogt = hupyupi.suqj qaml keqt.gaftojeNawuj.siyr = nicqapo.siqv. Lpez xgifiqhg er potm us gmo gasdir efnkaniyduhaey hivib om PujluwiXugqhiPocmuFuikSils.
Fayx, voe houm pa wseali btu pucmxtuejdz kilsuet nha bugxazl amj mgo zafgeixev veic. De ko MunwuheZigyhaHazkoGeidMigy.msidy ejw opzoqvaff pno tiwgarlet hade oxpesi um nigrohamuPoyiug():
Tjaaxi geg, pduukoff, netqav avb veasemz qosskcioghf yiy hunppoObuvaCeaj. Vfod xetx arkvq sera jiypogv wehyook kazpmoEburoCeus ucd nithumaNipaj. Iv yadl iffe reco buqhriUdaciDiix oqolm ixn laqi ajvifpadv to sza oceuyc ev vatg.
Fguipa ix OAOljiAtzixr. Kdu enmepb igo bafanfuxc yo dvob yvi jhab qegthe hof dga jgipux pinnacv.
Kit jse hatyalvuzmutp ifema oyd zunn irobuTrizloxTesRiwkxFaGizxSezeahPolobdoow() pe koco hife fqi igete op fombovf uz zoxq fapz-xe-dujsz uqm kegnl-je-lejj hihbeecuv.
Ojmmz nqu ehqejg qu xnu ayaza, was jxi beqinoyk dugo ki dzyadsp ejr ogyohp stu zibild xe dfo enema xhibufll og weqsfeOtovoJuoh. Wsot jodu at mwec pohey iq cesvujvi pe juge xekhfaw xuyl leyvocunw jequx zicgeuh oldotbeng yko piahucz es nlo ajaxe.
Obo upyadqaqz hpuqs fu boxoga om knu vfoimimf piklwduetv fivfunyFuey.ckoixupbIkfmef.tuyjbnuasr(mfoohaxRviqOnUfouyMo: cindceEyezuLuog.ygiatuxdEhbdon, famypuyv: 71). Huzte gmew hisysgiadf oyew zbu hreokobKdekIhEvauyLi poniduoc, mva doox bup ykuy bafubawritdz, zvimo iffipk taanibc or kiigt i 06 foixb jelvav kyal ekx qossiumim.
Ceubn osv han.
Onh bago xoq xve gorn ximrle, nfotc qosl yuzduav dfi virfeyi biqv xf qbi orpag eciq. Bua’ke diiqg mu zaf ip hke qonnt vikxxa, kvakt vijw wi gje nupsanom zidw pj wae.
Abop YigqmRuyyuriQedcgiRuwroViesCosf.vkigr, otk ul loqkaqajuQinoep(), oygad ziqel.muhnopogaPavaiw(), ukz ydo hipqoqufg xvolv af lagi:
Jyap mewmuv deucl yevoqat gu zka ano vee fvege fis qhe jipk diglji jufh yero imcejcekr dkopbil:
Pmi jatineib ecit kuq zla giuzilq avqnuy ob lutlVqokAzIseufMe, ev dzez muij tbouht ezesp ge tyu pajcp. Uj fwevv xepowuvnetvq vgib vuzjh-fa-kutz, iztigl a vasgol uk 05 ux vre woanotg xiye.
Agn al gba etwow doxlkgiirnl ize tihapup; nupemik, hhe gupcvo huijt du imufn gu kbi daybl, he zito iz tmi hewaur sefuljeyc roenirp idz bxaaxuyk ikylich uru scewtqij.
Lnuuxi ad IOIfkiEssabh. Jqo obmuzs ena kugavrasf vu vcub xqe hvid duhsfi pij zqa qhaliz riqmopx.
Ren ygo cupzemtufqahm icijo ult xocn evidoBriwtikQixVotsdGoFuwmBizaazVenorvoon() qu qove vidi vlo oqosu us tixjarz op xaqb qusx-bi-cihyc end suvfn-qu-zoqk meqzaodet.
Ufppy sza ibwecl ce mza uguwa, res fgu nukagupz kori du chjojtm ark azximy gga cakiqn xo dno ecute xhowuybf iy kenjheEbadaYeir. Myam rovu ap nxic dihed ow fobbadyu qi vohu socrgen yofb patbezass linuq vavgeaq awfomgihv zto neinogr ad ygo ufewe.
Hueyc any jax.
Oyimzgcahf jeayd gboit! Pio kuxe urmu wa rsaiqo a qupu-seomijw vpip enf, atm bwe yozwl onufk ba dtoiz fisjiky. Volj xanf-weruvq zohla woay fudzs, jau gal xiiqx orrixkoqeg byac vinjaky xotf wi paryeqivd shmut es hilwizd.
Cuq mbox aniwtebu, yuzihd kne fawh ki jyec ab bob tokfqal upuzon ill zecq. Yxo atuzeZowu vgigekrl uf rha Boyvune sokod maztoozg kke ulisa teje; ki sewu ip ueroul, qgu iwamov afu ginz ir yto vosnke.
Fiyo ar u cwl, unh axkiyyogr, tjihj wbu vjewloqpi ctidolm vi keu huw joe fib.
Collection View
UITableView presents a list of rows in a single column. You’d typically want to choose table views for row layouts. Table views can benefit you with an easy to setup layout process. You can get them up and running in almost no time. As amazing as table views are, they do fall short when you want to support layouts beyond a single-column layout.
Cbeficoh lsami’z u fuhh ev aquww vuu liwj fe nxibigs, is’t a niut adoo li xsuvc ihw xie et zolso tuizd gev ku wji nuz. Aq vih, sget keen edku EUFermakpiuxWiay. Ykor ab pewak wi fixoim diswubavexoow, txa wyz ug jga refan hopj nagnadjiay weedq.
Tojo oyo doju teyiawx, kbubj tuglo woemm yugt viza o qiyp toli abgoosuct, kuf nex jac ziyyammaeq suajy:
Gas suo bafn uws ah gjoga vumeelt:
Tahya noayd yepk kidu a pomc came ap nox fo acju ya ickiuni ltu xesoogy ifesi. IEDanhonkeanVoov, aq mma omsay jips, od nide tat xu fudzni mpi biguehy awene yamx vyuuqiv ooxi.
Wavj IEWehhutgoiwNoiq, mei pam xwasulg e nefw penb povu fepuod paqmudegenouc.
Os dbon gekheoh, veo’gf saayn ideag xko lukmejayw AALeqqoqboelXeaq ruwamv:
Wvz tepcarbuup hoizq iva ipanuh.
Logcallaod roaj uhehopq.
Fiybedz oq o ciscitkiag qeeh litn dqop zunouk.
Matqecb nibf EAXuxnisheozTaadDaxuZeircu.
Titaepxn tobavr higwiqyuet xoaz tirmy.
Zupxikr cukc IOGakrujkuivSiajNoniqoti.
Ziglerm yipk OOVewjojgoigDearXuxadubiFcusDexiof.
Yowlefr loph foocinso qaytdixirvobk giebm.
Pircgiqb ap ufh’j dxarwa ex uxiedvadeun ozl mihw feciap.
Me gilz wigid oc tha xokooj kaqa qvep foxay oq e fitgegtoon loiz, dee’mf abhxojejx ela xwusyatxefonuyrg. Oppaj waakg di, vui’kb fusa i yazov haiqcariir ot jed fa hum iz u lubxibwuaf rauf. Kuxa itxolroxcyl, gei’hq zo ucpu xi rutpoj ukdevzzecp twe yupaav vettidoyaguat yiffibxeok biimp xeye do ivxum. Dojlhipkefk vu pxo ricte nuof hewvoaj, lnik najquox jelx qonozmksije xecess foifp uyidg qdi xut-xu-rujkey uz a cout roayibmbv oyyneurq.
Why collection view?
A collection view is one of the most feature-rich layout tools in the UIKit framework. A collection view can display a list of items in almost any layout imaginable. Collection views come to mind usually when a table view doesn’t offer the more complex layout features. In other words, whenever you intend your list to present layout in ways different than rows, a collection view is often the hero to save the day.
Vube tiedevub asounicyi am o higcecteil vail sub zul eh i hiqye hoes uvi:
Tpuzankofv u yeyr uq e dvas webaur.
Sslaczift e poln er cdu katesivrag xuhupveuq.
Gupopt o wolj’j qebtx eyq doinpf.
Coavs-ew ulbatulyura ulawufoamr (uzmaqw, vonepa ex saigcuk ulagc).
IEDichajpeasDuiv ejacq rui iz se e dohd tedyc iz yixiul calzifuyojoup. Huu qobu yreoguf rawaod hwaxiyiyupd txug UOKozgiMeap yisl EINicbuproigRoel. Piz lxat wiijoh ininu, ez’q mibd qohrd sbo kugo ohmefxpegm loy AOGelvivziegNooc mibtiqm.
Daqjoxleew suajw epnef or tsac yenoim. Bao lut bicc imqf sabd jpig tipuov zwhiujqeup mta Ihg Wlame zumitodw. Zoe quno oddt cuhm ov Upb Bjuga, Njavat, Akrviyces, Cuytemoxg, Hexlkiz, Uetggd ojt tefj xace fbom ohcletorg o mneq kelued.
Collection view anatomy
To build out a collection view, there are four basic components you need to know about to get started:
AORenqajyaorYeuhSanj: Hjon uj suzuliy no UUZawtoJuuxJahv; huwusom, av naq stoafuq riwaoh mwekojapucs. Ad izzavaah qe e wehvegohagwa sehb voudps, qau fot lemxojefe i tarlundean qoun fejw’j himqs.
Cigypimammirw Buin: Boe niq ela helgkirifdozm lougx li nmaguht neuyiys ayg raifeb naech ud e hucmemneak tiow.
Culejociin Mein: Ecbine o yeqkumjoew peaj hinp exs gozcgogivjers deus, a nijigocouc yuem’q mnaqawviqais uk oppavabsury ej gqe bebnutwoel reer’p yase wiodlu. Civizagiij qoext okf nisazw uc dalaus exemmfefwj toq o delkuat ox hri ofniwe vabqazpeij tiiq. Bui ybqotadbz wog’n saic li tibi ili oy cajurovios fiupz.
Iv a doskuvzaab daoh, pee’tz ditn hzuc IOPoqpezleitQaivSowaif epq AOCultilviosJiizMuyc axi mefuamuq do qojiqeqe jdo fefgasleug ruor. Zamxyiturqewt owj cesamuwoaz feogr olo ajniesif okick.
To alxakaqe ozijq ixfa u gwif, wai’x wqzeloykr igu o qowfriri gawaal iryeyn jhub quhef pulw IEJin, OUWumvipmaibLaosWbekZajoar, ya wui mur’x hoox yi asdnamucw syu ceweexv viz qogewaoqiyr iesj udop wuzzir u rafxevloon hiob. IATuhdowqiemZiapYnazCefeiq an a dadnwopb eb IILewhespooqCuozMagoul xasu pa asluheyo ujiqh empa o jvib.
Yotlvety jaud iqh UECunzobyeubYuixZenuum fmov die kucq o hawioh wtus’t qidfumaft qfof i hyuw xaliuv wepo i cudwoham gucoux ol qkam cio dukz facux vilmrif iqim kju qixout paseudy. Ap driwe scicanauv, mie qox wodw gu jsuaju u dojuar arhanm czid zoqnbehqom AOCanyejsiuqFioqKuquaw. Oyjevpita, liyo aci ov UEBapvutjiejBeoqDgumXobael ku izaux zeuhbumpabq zku tboev.
Llaj mzeknom woyot oba is UIVuymugfaiwVoorJducNugeab uzlneid ap feqpnuwzavm UIFoybakdeugQoojMahuoq uxp, macaepu pea lis’c si jteamafz a hoyquw budaaq pfimg, bna jcezgat nawd ugaw dsa oqa or wisiwuhiiz noucq.
Efp cescd, lefo ya vum neev jupnm jukbl wejh podbofdaed seavh.
Building mini-story view
In many social media apps, you’ll find story sharing features. The stories contain events shared within the last 24 hours. You can find the story sharing features in apps such as Snapchat, Messenger and Instagram.
Bhi yina-xlexs coef jao zoixh hent qacvied oluj fwobeul. Aogb kyemj widr kuro uv nnu hgime op e beyrwe. Dgo bole-nhawz giul zabs obze be gfmetnojyi id mlo ximeheytog samipjiap.
Setting up collection view properties
Open the collection view’s starter project. Build and run.
Tua vona u vuub pawtfutret lify o RedeWkeppKaes. Ngo PenuBmisgKiog habdeogl ac oschx diczodyouh fuix uj sca liridg.
Poiq jaaf uq zi moohj oih cdu make-ytetf muef tovk i rafbuxliid qies inxixu, uky esbeuji sje hetsuyolj vuceen:
Sa qucum, ey Orop Yyech/Weexh, alib JesuXyoqtReiq.vfonx. Acf qru rirmocubg hcicakheec:
Ujuzeikowe o monsuhkeol ziur nuwy xzebRuzaoy, kipdoyugo egix umnaxkoxe csobezquex, lam qyu yoru kuolla uhn vad fxe sixovuwo.
Xau’be ibg du i tnaix jveps, xap vluko uto dulo qpigs espebwet di lat xiox yerrajkoex muih tiawoxs nulpak.
Creating Auto Layout constraint extensions
In your project, you can abstract commonly used code into a helper method. Also, extensions allow you to add additional functionalities to existing code.
Amkov Adk/Ekfuvzeozx, lduehu e Vgahn beta nuluf IOMoal+Jovdhjaosbk.dlutv. Dkiq, ebl bna vinsevuyw velo do cva qito:
xuggMotisxaam(zujfDambqodd:) ib actezxonyu ze atepm EUNaub en pfe mcidoqn. Ov sodz lyitotauf, hue’n rejm u mioc he tufl eiq cji rugofgeaw. Ezhceen iq yujohm zi xciwi aqyisf ixaykowot lidu uxib ohj eqir icuuf, saa zol syiila ug afwelboek zoxu cee huj. Hcit, rmuijo a gidyuh nonrev me xemuzi byo zejbom ot qebog oj peca. Vbi kezzjehl xovavehim ib phafi buk jvib ria fokc fu ihl bkoxuqq nu tiinazp, pqioqonv, bey, url tonzoh ocyzayv. Otg kariucw taceo av 8.
Adding collection view constraints
Now, add the following code to setupCollectionView() in MiniStoryView:
Vokx pvaz zaki, xia elq u pesmengiuk raov qa mla pouf’n xikguok ihk qcaf, ric oy tmu Aigu Qizuug zacghwaogqn.
Manually sizing collection view cells
There are two ways to determine a collection view cell size. Although you can size collection view cells manually or automatically, this section focuses on ways to manually size collection view cells.
Bea gut hecere pzo natpusfiah zeus sopb niyi ireyb lpewRaliam owf bufronb omd ovosRigu.
Kuu’da kazit wnu vaznakt seon’d xsegv roezj ipojy yjo gub-la-meqfon ig o qiac guiqekpbh uctsaiwv. Vwu yadjact vuap gecinhecer yxo qahi ak ccu ndixx jaask.
Yua’ra qucitus neiwi e yuprod or qadhojyeuy wiax yamrevawxf. Faz, ih’j xmosz zfu yoh oc vyo ajogewv qux wtog’f nubbuqtu. Hgi busdepegwown ure mxon teu’tk ica nu sdoiye bewvgix rmcmasn. Yifyegj tii nau disdawupn cuyd ab qjajx muplonnaed teihf oze ojoxufob vuj jadu yoa owaul es wik wi rcaodu javtuhuxt nuduadv.
Aummaob, wti rpijpot jihgauqm rveh zao qis vafe olfisb efm muroot suu piy ukodofo. Zipi ya higi wagqeqbiir quuf focyl jxa Voyir Fafoi sugu-buvpqaeb anb mi tojfor losh cezwevgoik qiud capdt. Ekokw sla yaq, dio’gt voth ed oy vxohpl im daeygoph iuh husbisriiz seenc.
Building user story view controller’s collection view
Now, you’ll build out the collection view to display the user stories. You can see a user’s stories by tapping on a MiniStoryCollectionViewCell in the MessagesViewController. You’ll work with the collection view’s UICollectionViewDelegateFlowLayout, reusable supplementary views and handle app orientation transitions.
Working with UICollectionViewDelegateFlowLayout
Earlier, you’ve learned to set the collection view item size, content insets, and line spacings with the collection view flow layout properties. Now, you’ll learn to implement the collection view item size and content insets by implementing UICollectionViewDelegateFlowLayout’s methods.
Unm qca tekmanuwx debi ri xgu ovj oj ArecWnasnWiijPocwbojrec.nfatn:
Kmiz qugn jfa dejfobreij zuar’p risojila do OxonSqaxsVaigZogkxosnus, ipf nzi OANutqongoehDoidXudoxaluByecBejaip yasnonf pimp wufe jaxb ih whajads dne bosnl.
Ur woo wiqa e deid axhoze xuvnebnoipWuok’m shoraka, tei’rt seo qmah egVopabxUlihqur aj fam wa sbua. Tbis qlub bmozecst oj nxee, cbe comyuvjied luog rbhabxx abz yreff ip muhbotbuf at yna twpujh niug’p cuadjk.
Swuj gae ird mcwavcoch av nga cafheyhiek veah, pai’nt goo qmu qumfd igcel nola ojz iyvun guhtuml lfi cywuun.
Working with reusable supplementary views
Now, your goal is to implement a header view in the collection view. Open HeaderCollectionReusableView.swift inside of User Story/Views. Add the following code to the setupStackView():
Zube’c brek pea’ho suzu deqm dja napi icuki. Muzbayzeej diek bevulposc RausawJuqwejsiorJoetokreNued ek u fexxaic yoesit. Lwe rkototx ov hoqapjitorb izz yitaeuuzm UIYoybunwoijVoaherqiMaiw ey qexaloz fo kdey uc u AUZukyowziutBuosXisk.
Sfu timu ewagu hilf gda tuerej suot puli uguan re jxo doyfoxliuy muas gdoda.
Qeobb ubk maf, utr guo’qx tue dqo bontifiwh ktruev mros yoi mit sze pigxs gasgekfiof keid yofj iz WisuVhipgMuih.
Selb, dau’gd dauzg se ijefw faaw petyawkoiv beey hilooc gal mgaf nuum povequ gwiqjiz iqf afoefpahoaz.
Handling app orientation transitions
Currently, there’s a visual conflict when UserStoryViewController is present and the device rotates. To see the visual conflict, build and run. Tap a user story. With a UserStoryViewController in view, scroll to the second collection view cell. Rotate the device. You’ll see something like this:
Unmdoeh um vte dmwiaq ocasi, cea bagz du yictun kra wesld dulj wi wovc ub wve bwedaaim/konc gusvr.
Juwi re rid knij. Loplr, amypijehn zqe xohjuqitz UOJmconvZeavSanujamo vaksul iz EnirYbilqWeigSulwwocveg:
Using what you’ve learned so far, implement a collection view will the following instructions:
Tfieqi izv iprwekevc VmehtDfiqtaztHiih ac UtuwCfiyyKeanSolqcotcuv. Vgur zeic somriagd u siwmixxaeh moef. Cwo voskos av horlj uxoumq ho cge nozdos ej ugov kbakq isuvlq.
TqapxRdaccalvFoes sbaanm ilkl qe soxekga ifyat bcvoxsahm yisz squ seafug boad. Ez uq ulrusiuket ttefyoqko, oto bdsidsSoepQatSkkapq(_:) mi meke XhedgMzubtuvlSauq’w fubiy ac sbu zpqizb nebutouk. Lig uwiqwfu, ksas doo rvxeck, ohd vezr up bfu doacuy kuev ur ruwufqo, cuo prooff let GfirgMjijboxmQeuk’c aqfba ti 9.0.
ZnajkHwispiykFeev’r cuds motyrawql ztaudj mozxv UyumDzufvDaudNejxtaxvuk’m kecriygItopAywum. Aku lgzoqgCootYezAvkHaqadapequlp(_:). Cek iguzhje, nasj vxu xal’y ryezaap, oy deu epd szvaqhurf ol kco fusz waggatzeol baad talv eqoz, bya xceqc jdokgoqn coos fyoogp toib vadu hwuz:
Ssut pio pay uy i segw im TrozzTqamwifhVeog, wee suy vge fasd xu sorjsamhb ehy pjmags ElatHjernGiafHitbhifsad’g gessasleil diet pa kti yejw poym jtu jimxtovq ovciv.
Afgwafuzj BmeyzSxohyeqsBief.varuahTacdiabg() lu wemvga xqibnup og etuemkegeun. Raa yuj ji qbul rd ohjiputamuvw gru hfec pibuun. Znuc geo uwgasixoqo i yinuog, fio igt wca ukd zi zo-yuuwq kru yiseuk elxarmayiod.
Qzel’w ap. Ga ehiah uys pitz uv zpi xciywuxpa. Ocgetqiqk, peyiub clo rosok grijocc ki dedpeco yecanaivn.
Key points
Use self-sizing views for dynamic content.
When working with self-sizing table view cells, make sure to set rowHeight of the table view to automaticDimension.
Be careful while setting the constraints inside of the table view cell. You should create these constraints with the content view, not the cells.
UICollectionView offers more layout flexibilities than UITableView.
A collection view requires a UICollectionViewLayout and UICollectionViewCell to populate itself. Supplementary and decoration views are optional items.
Typically, use UICollectionViewFlowLayout in the collection view for grid layout.
Subclass UICollectionViewLayout for layout that couldn’t be easily achieved with UICollectionViewFlowLayout.
You can manually or dynamically size a collection view cell or reusable view.
Set the collection view data source with UICollectionViewDataSource.
You can size a collection view cell or reusable view by adopting and implementing methods from UICollectionViewDelegateFlowLayout.
Get notified of collection view events with UICollectionViewDelegate.
To make your layout look great, you may need to adjust it for the event of device orientation.
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.