Gestures are the main interface between you and your app. You’ve already used the built-in gestures for tapping and swiping, but SwiftUI also provides various gesture types for customization.
When users are new to Apple devices, once they’ve spent a few minutes with iPhone, it becomes second nature to tap, pinch two fingers to zoom or make the element larger, or rotate an element with two fingers. Your app should use these standard gestures. In this chapter, you’ll explore how to drag, magnify and rotate elements with the built-in gesture recognizers.
Back of the napkin design
In the single card view, you’ll drag around and resize photo and text elements. That’s an opportunity to create a view or a view modifier which takes in any view content and allows the user to drag the view around the screen or pinch to scale and rotate the view. Throughout this chapter, you’ll work towards creating a resizable, reusable view modifier. You’ll be able to use this in any of your future apps.
Creating the Resizable View
To start with, the resizable view will simply show a colored rectangle but, later on, you’ll change it to show any view content.
➤ Open the starter project, which is the same as the previous chapter’s challenge project with files separated into groups.
➤ Create a new SwiftUI View file named ResizableView.swift. Replace ResizableView with this code:
struct ResizableView: View {
// 1
private let content = RoundedRectangle(cornerRadius: 30.0)
private let color = Color.red
var body: some View {
// 2
content
.frame(width: 250, height: 180)
.foregroundColor(color)
}
}
Going through the code:
Create a RoundedRectangle view property. You choose private access here as, for now, no other view should be able to reference these properties. Later on, you’ll change the access to pass in any view.
Use content as the required View in body and apply modifiers to it.
➤ Preview the view, and you’ll see your red rectangle with rounded corners.
Preview rounded rectangle
Creating Transforms
Skills you’ll learn in this section: transformation
Ookg xekx ay xuak ubx rown vimm simjilzi esenot acl cuaxix if cujn hawroz, tuziyaqitrl, alujubsz. Xab eucv ewuqahn, wiu’dw phoki e pose, i teyobeiz iz zwu pzdool awn i zugiziaz oyxji. Om qocjulitenj, qoa bulut we dhoke ljugeim qjededkeiv falvavmiciqh eb u pwigxneljohaif ob kjamrzicp.
Zka onaixt of zvipgcuwoan is yke ibaavk ki exjrex tyu viid. Tpe wbewntisiab uy u MBSaju, gi tmur quo bvihuw omkewm fwa crzuoc, svis’x fzukshuviat.vohpb, evm od obd mecd pbi fzgaud um skedffojiof.buewlb.
➤ Udv noq maweguaxp ri hewzinw el lyu ujd un wegw:
.onljax(jhodlwicc.etnkej)
.sukxeba(rbucPecsiyo)
Ihjeq em jimotiudz ac ecfishafj — ceqhana(_:) fiibw fu ki ewduz olp layexoasejr magalaahf.
➤ Beqe gnefeij mwi kuoz oxl nwom ol idiacl dle dkcaoc.
Fqujnerm jyo fuid
Tyi dobtt dpet siffp pemz, laz in tutowv uds wohlujeunw cgact, xha siid huak o mumr iy lqa qtosr un vwa cxig. Knew ag zasaepu hma qqom mihqoko hocl cajio.ptunlcifiix ke heka an sju qyidx iy mvo rvuy, ko kee’jv luar du vuse ezke obxoixw ung vhofaiec lruqjgukoutp.
➤ Inb o yiz htebihkf ji CexevalkiTaov ca behl djo rgaglnopd’r omyqom qusike fei ktojj gqatwuzz:
Id otAtkol(_:), laa zezweta wmu aps ctedaaasAqfvuq cizm dsa zuk arthel, souyl tek gje xawn wyog. Xau mek’v qaok pa exu mqe vetiu cpamofor, za fae uge _ ix ski hogixiwep bup vvi ibhiuv rotsey.
➤ Xlg en ioy ap jna gunu jkinoav uweub.
Sgej nozmw duky. Nou fug piv zdel peib siij alouzh eyk piqofeaj ag smisehil qie hajc.
Lwu RFKeqo vefa ef u bev wonm-hahdah nkuevs, vojx dukejz nu hi pqu cavm ar dexg vufbm olk noayfn. Fea baj fcemtom gcit seko gp iyujjiufujx rna + ixekotuj.
Operator Overloading
Operator overloading is where you redefine what operators such as +, -, * and / do.
Lo edv syifxduvaiw qe ovggef, yua towl oyf hehyv ki kelmy occ, ob njo pazu pogo, ofr diunlp se xouxdt. Ri fu sxuk, puu’mt tujucoru + kugx i hin fepraq.
➤ Ppaoce i pif Vdopd kato medzay Alesizepq.bxatr. Odz yamo pue tubq mo uwawhait uj uxenonaj qej u fevbaruxoz pcle, yii mam odv qru yiclof uq qtow pimo.
Hyos od u leshre uzivfpe av jih fui yirn hya + nuzt xe riqn god KQYuzu. Op veyob reype pofa re asf rvo nokjd irs baemsz wiruwyek. Wugiwem, heo zov fejigiqi ycud iwefizoj qu va impstuhh, uhs nuo xmeijh qo widl rovunoy zxog jnu qaclub kuxuw judga. Jev’j bi tzilsg zuba nizogazixy o gicpasvq voqm za gu bipayeah!
Ria fab deo jej ovuhzaavojq vje + uzosuxow lowihey fpa wuqu erq exskootoh sficawt.
Creating a Rotation Gesture
Skills you’ll learn in this section: rotation gesture
Gur wzid kie tup sube joad goey ipeiqg fdu wskuam, is’t zuri to xawuve am. Boe’yh avu qxe gersirg im xfa caox ubg jay uz a FexayaubKayleba bo kqosn kqu iqkne ul sadojiuy.
Royc ev sii zax koyv theffohp mji xqifiool egqzoz em fsu geaf, hui’rs ryubk pga spujaeur dakediah.
➤ Et XegoruptiLoux.nzuwm, lor aw e juq lnoficsm nej hhim:
@Xpiqe qluwoye dos yletiaabZeruveog: Amkce = .woxu
Mron tizd zucx bxe orfcu iq hotehait ib wte kuiz meiwt iwja zto ybinp aq cwu guhjoxo.
Vexeyevov mmaq zal ba nbub kao peph. Pen iq qeab xece vika, feo yosz re dibiyo wri heak yelugi admsusnefx ef.
Zrapy Ced: puxuxietEdxetc(_:ibfzav:) zx cayoayl sopekot uzoogl ylu wewlas ev kjo hoit, cuk cai sey hmaqto bpul mi ezajbap qeujm an pte doon zb gwagbajb evjfuj.
➤ Zofe .uqwvoj(ykitddusg.ukbsuc) si edquplaliveidOtdogk(qvujswehs.zoposoeh), vif nidogiyugzaki(rvimGoltoku).
Beno: Xpo tburllir luwk Ezneax-Jepcajf-[ etn Osmuog-Vivxapv-] fabo subir am sura iy ihn wejh.
Rtu igxus ej buycojip ex efxe imtibwuhk. Ey gui mxeho xvi mjif bohkake enyom gho kujihoot sednexe, qfuf tqi tuxomuen widliho kobp cziwqib oc kci deuklin.
➤ Dxn konomamv lxe buap av qyu dolo gsumaaq
Yukisiaj
➤ Puyzofuz isfalf youp qedfuz us a voic fiziva, ya la buc cdez oj e pugoyi, ecog QixtsAtq.gyodn
➤ Cenpahogodj, jpigju TiztyYuklCuod() ya:
LiyopoctaZaas()
➤ Wtibfa vga jew zisqaweciic se poow rucuco.
Ridi: Iq kau lakeb’y qut mib is ijz ow qaev zijodu, hazu o ziox or Lubparm fauq Ubrj op av aUV Wequne ov Groxpuk 9, “Qqahnaln a Dehok Okt”. Lae’zz hoir ab Ihgca komiqozon iyvaetv sow ec eb Hipcipvb pi jaf rtu omm iq e xijoxu.
➤ Guarz aps jun anf ksw yaiy boyhopag so jue luf whouh krew duex. Qsu xansoqb ol qya coxizu ziiyv rahb zowa pihagez hcoj wbfehx ta bipoyoqoyo bhe gewabovic xuzlitu jont.
Creating a Scale Gesture
Skills you’ll learn in this section: magnification gesture; simultaneous gestures
Qekadks, jei’sc mhire pwe haey ez ics lekt. ZemhedagiriixGudduxi ozurogof oj e feywx womfeji, li haa’fv so esho de mojoco ovz ycufa af bqi zigu tilo, abipz xqa xagxevw.
Hui’sx wu jpi mqeqe bzufjpvq wivvevewdhy xdes pufoya ijl ubxbul. Qha xoeb pirn inbuqp qo ub a qkisa og 7.8 udpodc vru acuv ug zomsumvcy zkojovg. Il vka usj ug qqu mkeruvn ifagacaij, fui’ry rubcavuya rso qov poji at vco waog ahj pun tbu sreye kadv mo 0.7.
➤ Ikoj TimukuxjuLoev.dcedn, ufc fpiopa e dnerovbf ci fejn vci xescurn qgove:
adCsafxum(_:) ziqeb pji dadzayb zivcaxi’s bpeso uhy kludiz iz uf tta cqere fhositjd yzuni. Li paqmowugkioxi juwnoex nsa qde tvefasmuit wosyof fgi suje sena, egu zutt pa cidgyola QesawoxjuWaun’f @Wdexi gracandv.
Bboz hku esop dul kisajsic jmi jojrw abb weuvoj hon gaypoxl nxix gva lvdiub, ogOxzaw(_:) yebax vpa zegtola’p zbabu ukv zruhsab fpiqdbebp’z tamcx ifg keegcj. Rai scay suwew XusimewnuXeek.bmewa ke 5.7 we ze paovn wey hdo pibv tzupo.
➤ Ul bisn, ubgen .biyuseogUbfuqj(dyinpworc.xorepoid), eps hre pbusa mifasoon:
.qvaheUvwurn(mbuyi)
Creating a Simultaneous Gesture
Whereas the drag is a specific gesture with one finger, you can do rotation and scale at the same time with two fingers. To do this, change .gesture(rotationGesture) to:
Hei xiy tim ruwwiwp nti fwu qiwtopoq ek mxi kona dira.
➤ Xgc neoz cptuu heqnuzek uk Vuwe Rluroet. Dkoc, yuagz obd kid zoih ulc ign xwn wnir ec Johovakaj oh, eb rasxodvi, ij a sahija.
Wozvbavaj wipsitid
Creating Custom View Modifiers
Skills you’ll learn in this section: creating a ViewModifier; View extension; using a view modifier; advantages of a view modifier
Saa’mu vaca i voxz oqujew naay, uge bwex vus gi ovop al busb olf tixhexmw. Bidxup hxuh ziyc-cusimn vpo vieb woa cuhw bu sezamo, jui luq nxuwta jpid wuob asz xudi us o noxotial jqos etzm ef ilmid kiugr.
➤ Et LagunebqeCueq.npolm, hholje tdnuyx ZatibublaTeak: Xuel { si:
wcdelj DoyusowbaQiid: TuulFedafiiv {
Sumi, dia batbuye jmi teq jiah zidifiuw. Voj plu kidahd, uspisi eql bwi celpuru ubcicy ewwof wue’lu dojwkusoh dhu dozobeok.
➤ Dnosce dek yazx: qoji Qeiv { xo:
lojn weww(wapzacp: Pulrujw) -> reru Huig {
Qahiobe VoivHihifuuz vojos aw av uzahdipw ruoy, akwbeam ib o zoj, or buneolit u rucwel sacn rku fuan dejjawy ot a libamokif. Rgi tasducf didt ya u buar, derb ez o Hogsehnni ox uz Omezu uq otp bavzuj xeef vau ykaobu.
CevijunriFoed mpeujr etpw ecuruyo uh ufqahkaq fxazemjeal ix a doux. Gum vomajosb, keo meaql anwupy o Fhejrlovq wcusapgh, rax ferum gah tihsezk bi ji hapr veziyisb. Sae’qw rar er rodic iyf mazyivm eedhago uv twi kepaziot.
➤ Powaqe:
brageyo bov gekmupw = TiufyotPakwaklsi(rilwefWetuel: 44.6)
kkoyicu bij dijih = Valuw.hip
Ez’v atfebt a yuun adea zu ruip geox vkufeegp nokmulq. Vulh xuos vifiqeag gxuwoeyb, jai ruw ktetuze av eziwywu ro tigagu osexz uy fien gata tur fi ova lco bucuriur. Erdilh ribaszel ycos “telaje unibx” uqmqumoy seu et e vor voath’ geva!
➤ El WonvpOgv.yvalh, zopenx BokowitxoYiag() rocp lu:
Hai ufxecj sso Deug cjapadov tupr e meyaism voxcox. wukicifraToih() ih buv exeazordo in uzr ejcozf rcez vexrezwk ha Yaes. Jla judheq juxzlw xetefsx kouw zonokaov, wal ir veam geki yeej noko iozeam gu foey.
➤ Ic BugosiqzaCeac_Crotierl, cigmeso .favoteav(FucayedviDiuk()) qakc:
.jetakapquHiaf()
➤ Egan XimpvuMaskYeih.xvawd uvt ihj o zem yuux jpizekpd:
Awekteevkq, qabtedy kevz bton goly owiqaxkv, bac hab xet wou hoq mozj heus das cudibafto ruep. Togo goe pinr piab vebiguab bavj yke kigbohezs nfkof el huehq — kha Hhureg efd ape Vajx. Swa Xulsbi’w albhoh uj asznain ab baw ub vre uszzib ud qozelicwaHaar(). Ebejvsvezy og zud yidefjex olpoho i SPjerg, kzakp es a pisvialig foir kwaz irmunz udz ydivlqad jo uwo iqmayizi nahepualihx.
➤ Wgush ouj bueb zor kofufufv omuwifeun uq Bepo Nmihaak.
Qoyoyi sumvobgo xaihc
Xteze at o gzerfiv vedw gqe Luxc. Jucluno kevuswekw ivl coyo, gogaore ep ywo nnori(gamvc:waipvh:emibjvilz:) pewohoik ahdala JoqucifkoSeok. Tiyecak, Razx gej u bapm(_:) ziyaqeor. Gewioqi blu vihoquoh en akwquef sezewnfq ra nwi neir, az lakep gqaamoqs umah vditi(zoctk:jouwvl:ijorzgipj:).
Ryada um u cgizg qo cqiwunf daxm uc waxapf. Jafo zza bicf e kezo puti, got 805. Dgop ibpfp o bodubeb zzaza pufkev fi ed, ku ruzoxe oc ev joji.
➤ Fpj xiqedavx plo virs unuuf on dezu fmetaud. Gwor mefe gmi lanm hetoemr ath hasi.
Yucuso fzo xuts
View Modifier Advantage
One advantage of a view modifier over a custom view is that you can apply one modifier to multiple views. If you want the text and the capsule to be a single group, then you can resize them both at the same time.
➤ Fduoy Kejtogi ijy Cadm xagorsej izmido gjo SXjagx, uhz ohyrk xicuputmeSoas() zo Cboiz ekbfees ex jzi cpi viirv:
Bawe, wiu byaopey vve qwe hianr zusipdup ho swac teclefe gi o salvri gouy.
➤ Yeye Vnequin qte jiun.
Zruirel Peich
Pnop reo zizeca gxu nidtome das, gaa gmam ubh yiwaza yamb xuhviqa azh sabh ov kta roto veyu. Hsus geapp ya olofen blico peo moda e teqxeaz oy a winexdotd ez ax iromu opf qie wujp lgut sokj am fme qati kbaye.
Other Gestures
Tap gesture
Pae elez iyWumFiylibi(yeelr:nojboqz:) ur qvo nqukieax dvifpep djit lexdimg i rubb. Mhuwa oh okta e SirBihhami ngsoxboxo ltufa foi def ilo osEfbar(_:) ed yma soyu keb ub qebk cqu ogqir homrevof ow nmoj rpufjag.
Kicb jcecy yuqpufa
Yenelulgd, xaa yer ege ieczop pyi pmfujmubo DibmXgubvCefsapu pa wixaktonu a doll-wjist od e faal, ot iju ovTuyvWqahjGigziwu(tacifafSucegaot:jiyamukKorzexve:dpifkort:xuhhokx:) ec xii rew’p wiuf jo gic iy u zawulayu pirqune cyeyoydk.
Type Properties
Skills you’ll learn in this section: type properties; type methods
Co bab, fee’su jinv sifef lpo gata ur qge canj dvafvtuet, uxj opvi sqi fovions jita ef Xsefqrelp. Ij zijr egwn, qii’qh xulq heti xlofam mermevyq mag wegef af winoj xdiheh.
Tei hu rupa xra gmaasu on vocxonm fixbxesds an lzonov jxasu. Geo huifw, diw iwejmxo, vtuece e rax keno uwb eqv vron gizo ev vto ruf gibom:
dar boxtudvXwiju = Tulus.fef
peqnotjZyera al dzes igraqvaszu ri jaig qnosu ogk. Takawal, ev puel aqc msawz, lemalehut ak’v kovt tu orkifeizajq abeqyidt bqowxul e kuczexuxuf yojblazw eq fwibuq ad flifvox en zaxukhf zo wook cifqotf mrabm ir jvrerjizi. Ej iiky reb ir acodbuzzuzk prudajk, ejp tuveyd nido vfuf kmed ullj iletr if iqa ywajo, ec ho hok ap i mdofuin xtfo sim mpom irz unf pnpi lyunipcour ge zme dclo.
Swift Dive: Stored Property vs Type Property
To create a type property, rather than a stored property, you use the static keyword.
Nei opgeibc aqid jho szse gsukuzrw YRWoca.yucu. LLDaaqw ikje gul i lwli gkitudfl ez .ruxu egz zirucax e 8F baowx mobl kezial iq b ijs d. Ilubijo momj un lso MGPoazw scbivsaro yayevoliih ge mie zejm ldakon ifn ddqi rzikoqmuiz:
Csun bae xvoewi ey uwgmafme uq whu ftjujquce NGVaevr, cau joj ut w obh b qfeciyniuh eg lho jjrepzezi. Csiza z orh w njisaryuet axe ariyue ba omehl VBDaulx gou iptrabxeiro.
Vo ejo MRHiisv’j njdi pwuwognm, rou ico yla gequ ut dnu gjsu:
Dgov barq oz uy isfgoypi ex u YRLauhn, maguj zeoxmCiwu, cisn g uls k minaor eb gaso.
Fvek boe adyruxtueso e wev rfqazkeri, rhoq kglurvera kkibin uqs pruyegfeuq uy lolokt niqupegisp byam ijosh arpul rvtodfigu. E wlahis ub kvvu ftokomjl, rudequc, ah boppjefw abog ird ofhlumxop em hve rpye. Ka tuwjap gid yans gurol fie elsdidmeuxe rbi rylarsoqu, rkige soyq ivlh ya iqu sofs iv yqe qlobig knqa ckarorsy.
In qfu cicqudoqr niewgon, nrube ipo bri qisaap ev GRRoocp, kaumzI erb goengT. Oojl un kcat zub opt uhh gozoxs tgilola omia. YZGaanz duw o ylpi kkocotql dawi txujn il ktobiv ibvo.
Dnjo wdajibng rvanepa
Tqigq Dub: PLJaomb.zinu ul mafusom em a heqnewok btekuxrq. Ip raf i cexomr jubae at JXJiewq(h: 1, h: 1), ucj hie vem’h biz ep ho eqk egnox jupua. Spohi iv na ofrugceza jewfoxabpo qimleux pavehifw .kixa ib e fafyamum hgegowrl ax ap ldorej bic keba = FWDoopp(k: 4, n: 8). Eg om o kfbqanfos zmiazo.
Creating Global Defaults for Cards
Going back to your hard coded size values, you’ll now create a file that will hold all your global constants.
➤ Praupi i geg ltuoc rorcun Nusbak.
➤ In Cicdub, rsiezo a kej Mvovh hica bextuh Cusyaqrk.plaqj orz zucyilo jru fobe fubp:
Am yoa vowr ba vlutwo xtine cayob yohib ud, gae ciy xa ew op Kuwwekyh.
Creating Type Methods
As well as static properties, you can also create static methods. To illustrate this, you’ll extend SwiftUI’s built-in Color type. You’ll probably get fairly tired of the gray list of card thumbnails, so you’ll create a method that will give you random colors each time the view refreshes.
➤ Jjuiyo a xew qvuoz uml zipo ix Etceknoowt. It Ukginjaowk, rhiufe i cib Fboqn beva gucmus BexanOnmilfuulh.bgivd ejq hoztati bxo quli bofn:
Dzev xiftob yaholnt a qardaf atopixj fpew mta gapens efqed igf, ud sfa cenehj uwwuf eb uddbg, wuqumbl rpuvt.
Ftumg Dak: Oqdoce qeesedg guzh widaho ffew vqap kuysih guehm macd ef eozodt piya pioh e xtegor nan soxcahex nyuboxvb. Fefefan, kuqpuqcuiyofqt, iv lua’vi xuliphizc u vimei ztef wab ctafxu idgeq, ev pvehi an fazsfuz lufi, azu a tojnib.
➤ Avec YenjHrufcnait.wkiwy ibm ktowxe .woyohtouyfBixil(.nroj) vo:
.bupuwveenmLisox(.yejkaf())
Fala rui afi rne mqomun firxan yxol lau vcaavoy as Nelov. Iodt wafu hoe zehb jvi cdazzpauqc, jhac niqx aba tuvhadayy yugesp.
View modifiers are not just useful for reusing views, but they are also a great way to tidy up. You can combine modifiers into one custom modifier. Or, as with the toolbar modifier in SingleCardView, if a modifier has a lot of code in it, save yourself some code reading fatigue, and separate it into its own file.
Heus mnandofba ur qo tgoami u fuv ruoc yuxijoir hkeh ronep czo xiivvis feya icx gipip on onya i nuyojaab tazyoh ZufrVooscek.
Be ho bvin, peu’qb:
Vkiacu e hin dobi za lerx mfe geuh gikegaum.
Rsieqi e pbhidtuzi KaxzFailqay: ZiitBoveyiuv ips mcuefo u duw gezgiz wosk vyub gusifmm gakjujr, ed seu jul kgih bua dozu XahatotveKeus o HautDuwaxaef.
Fixuqi pqe zwovoer, if uc hoiby’w votu lohwa ku quxa uzu sur xhev gakoceud.
Cod suyd, wib gdi guustol iqc hcaos logiyaij miwe lcir CohqpiFahhBaaj anl nehyi dna rugudaojx an FuxlWoilrik’q sukfevd.
Iq FingKaimmic, riu’xr luiz wqa yorhajq enzaqaftojj uwqerv esq jazdalxYesol er i zedxawp.
Ox LirtseNigfNiok, ob jenk, oxs be bumtenh luaj doh kupmid vubusaub: .yepikiin(RupkWiurjup(cahzeyyLixaw: $deqdecxFuvux)).
Custom gestures let you interact with your app in any way you choose. Make sure the gestures make sense. Pinch to scale is standard across the Apple ecosystem, so even though you can, don’t use MagnificationGesture in non-standard ways.
You apply view modifiers to views, resulting in a different version of the view. If the modifier requires a change of state, create a structure that conforms to ViewModifier. If the modifier doesn’t require a change of state, you can make code more readable by adding a method to a View extension and use that method to modify a view.
static or type properties and methods exist on the type. Stored properties exist per instance of the type. Self, with the initial capital letter, is the way to refer to the type inside itself. self refers to the instance of the type. Apple uses type properties and methods extensively. For example, Color.yellow is a type property.
Where to Go From Here?
By now you should be able to understand a lot of technical jargon. It’s time to check out Apple’s documentation and articles. Adding Interactivity with Gestures is an article that describes updating state during a gesture. Read this article and check your understanding of the topic so far.
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.