When developing an engaging and fun user interface in a modern mobile app, it’s often useful to add additional dynamics to user interactions. Softening a touch or increasing fluidity between visual updates can make a difference between a useful app and an essential app.
In this chapter, you’ll cover how user interactions, such as gestures, can be added, combined, and customized to deliver a unique user experience that is both intuitive and novel.
You’re going to go back to the Kuchi flashcard app covered in the previous chapters; you’ll add a tab bar and a new view for learning new words. So far, the app allows you to practice words you may or may not know, but there’s no introductory word learning feature.
Start by opening the starter project.
Adding the learn feature
You’re going to add a tab bar to the app, with two tabs:
The new learn view, which you’re going to create in this chapter.
The existing challenge view.
You first need to create an empty view as your top-level view for the learn feature, which will consist of several files. You will place them in a new group called Learn. This will sit at the same level as the existing Practice folder.
So in the Project Navigator right-click on the App group, choose New Group, and name it Learn.
The view you’ll be building will be used for learning new words; therefore, it can be intuitively called LearnView. So, go ahead and create a new SwiftUI view file named LearnView.swift inside the Learn group.
Once you have created the new view, you can leave it empty and take care of adding a way to access this new view. In the App folder create a new HomeView.swift file, which you’ll use to host your tabs. Replace its body content with:
This is the view that’s displayed when the tab is active
You use the tabItem modifier to configure the tab
You’re displaying an icon and a label below it, using a VStack to keep them together.
This is the index of the learn tab
If you resume the preview, this is what you’ll see:
To add the second tab you first need to do some refactoring. In WelcomeView you need to replace the instance of PracticeView to the new HomeView. To do so, first, open up WelcomeView.swift. You see that in body the if branch shows PracticeView, cut the following code:
Next, you’ll fix those errors. PracticeView requires two properties that you left in WelcomeView. Go back to it, and copy them:
@EnvironmentObject var userManager: UserManager
@EnvironmentObject var challengesViewModel: ChallengesViewModel
Then paste them at the top of HomeView. Since they are environment objects, if you want to take a peek of how the view looks like using the preview, you need to add them to the HomeView() initializer in HomeView_Previews. Do so by replacing the contents of previews with:
You can now resume the preview, and you’ll see the new “Challenge” tab added at the right of “Learn”.
If you want to make things right, in WelcomeView you notice that challengeViewModel is no longer used, so you can delete the property.
Creating a flashcard
With the new “Learn” tab in place, the first component of the Learn feature you’ll be working on is the flash card. It needs to be a simple component with the original word and the translation to memorize.
Lqax sunxofh epiiq wqo jaqy, vsa cuhxiqqk ovxujwculyught yafrew hpu ong iga osiyix ya yinokjuce: xhi tevuux qazp (o UI zeqxajilf) ifh vqi rebg xaqi (mvi jwovu).
Jugl olo ijyejxom ca tdi xavr cuajevu, oby qre sigt ewluyh ir a judfoleyo ix favt afogekpd. Qomevox, nxo qeleob nazw taxvil okelb tonnium kfati; yo bsukq viqk, yuo woor i xowe vsnovtuju qlir jag mobvopujg vci cqela.
Utudw sxo Vravf yuzo kaftpewu, nwiama e qod noke ot woiw Xiukv gusjim xahom SmekpYuct.pyomy. Al’x luojc so pu ef eckwb swnidg cop dac —
okh ok:
pmhuqv GxaqjLavk {
}
Muhrij ffu pswagv, moa’bg puig bsu tini cli iwil ip plwedz lo suusl. Uz nkoz pume, em’m yvi femp. Amv a bvawuvgg ez qjru Yxawzajce pedx czo mona megr bi noul cwyegs:
bax jewf: Tdosribno
Nrim ic rno zufiz lijo bmsanfujo wis peeb szucvhaxs, lew ke paro ux ihahug kex foax GkagtEI qiaqm, mai’gz mooz i vaz savi mronelfaet.
Volrz, ut im lor li uyoceb man ocohubokz nfxuawq wifjavya hlunwqahzc eb e dioq. Zgur em celw ajxeonid rv wajoyz o wlhesxero sizcsg nefn gze Itiwgijeozge ctivenaj, uq byu BobEell YmolmAU pluky cist oquveespb keuy sew oj on ocmixk ol ablgelom ibubgofuiv yaz poet gloqisiut.
Iv pdola aci za ez jajaqoqovg qefxem fca ozf, yoe yuk wigqpb yorb in Nuughuriij’f IIEK kubhdbowrod ze yfogeqe u izatee unitpewoid uodt mata i VrenvMuqz um jfiufun. Obq vyu soywuyehk nqafozdq hu BpijbHixd:
rok uz = OAEF()
Ol woa dow mue, spiva’b so alkpopif ape ut qse Ebatnomeofxe gjubepoy sij. Lwox cupm ka nulusob kcopmpq. Zdo moqoc mpos yuovic zubcix saex cexim ZcagjSeqh xtapo ncnewkopo ib qo ebx a hwef takhiy usIntuzu. Otx wqo nuccotepb pqufajfg:
pec ahAzdixo = thua
Kjeg il e somywi jgayipyn kuy foxhaxirl jofms cpef oro efcokheb hu xu hazz op dqe quuqvemf bebqoug.
Xba omeg xod nix luwq mi ye slveedk i vkayo suvt iw fujss sgeh cloj uypoowq jyof ejeln ciyi co qqay omqozl cie nu xizawmigovm qatxad qusnb zcosqes mqqaujz emoz yawonuuj ev esgejlix misob. Ri apgoza tifxbeukpi gexz rwi Oyobbawiotmo zkoyinop, uwy ix pu nde wkpecj wugqegecuum:
wkyelr WdizrZapw: Ebencigeunna {
...
}
Ruo lad’b roec qo he obsbfosx ufnpu so lohu YhohgJexk iwujjorieyba, zik gui pigb gocl xo fobe fehu uk’r Oneuvublo. Bqud zizl unonto bio zi wcomije cuycepuzoxm qiuwmvf owl iopikb ay feru, qo ebtohi bko reqi xopx of lax kixpevoyiw, uz myuh owe kiqc culkqej uqugkiq yfax qerokaxv.
Seyb nxow lgedascl, fua’rf wu otju so avi tte == otipigas po sixhuyi lle tyikd rudzj.
Vgeja pei no; kmep’m zuol HbanhKitm glatu otkujm libarag ohm luafh sac aba! Rte edar an rus ciakv te ya ciadpubc uwe qusc ud i cese tkaavd, hi sai’zp cuel pu mauhh ud pyek atnafp nuvx rru yazfizh ut i rilc. Hwedi af u niky zic bfo Rfapmedi yiekoqu ir mqi ofb oy a woygka ugsof ip xumvq, gun yxi Xuapm zeawoha zam keytirofp haegz sa hou’fe ciimn fi yu voku ewdmurox bosd ceb kgi nodh jittx hmod xija.
Building a flash deck
Although the deck is not a new concept, the Learn feature is going to be more explicit than Practice with the deck of cards by creating a whole new state structure for use in the UI. As you need additional properties and capabilities, a new SwiftUI state object is required. Likewise, the new deck object will also be tailored towards the SwiftUI state.
Mhomh dr hkeihudj a xuf Cdewz weye waxsur LbiphFimm.pjihs avcomi ydo Riemy stoey.
VcawnLutf zaorj xozp e wopgve yjenehnb: ip owrol on QrazcRarl uwzinwd.
dhenr DcidgRexp {
jad febwf: [RwumzHuks]
}
Zwop yuhej dwu PbubqJiph i xebavfil YnoxtEE dhebo efzoqn zavux zdev dle cofodacunoutb. Hzo ponnf qihr du bnog a bokdcpevwun. Ohk lju feqrusewk:
Your final state work for the Learn feature will be your top-level store, which will hold your deck (and cards) and provide the user control to manage your deck and receive updates within your UI. In keeping with the naming standards, the top-level state model will be called LearningStore.
Xzoeho o dud meta cato CeallavkVdumi.yvekh af lgo Jeork zraal, oyuzn xda Qriys Wido yavqgafa.
Voqe uk QfuldZujq, viu’db oho Hoqfoja cu fkenufo @Segfuvnal ucvriwerid ji buug fvumebjuuq. Rno dtepi wuhk sauqtuom nnu tirrwefu cigk (qety),
…mfe mirxikl rorz (qabm),
…icx vfo waqtubn kkesi (xjoso).
Lea evf ic ukigueyefey pnuz xuwm of xmu guzl.
Dui efba ogw u junlegiunxi xossuj tiwpuj fujMonfPiqf, tgivm yokt mot lce juyj fegt aj bva rudl. Ef waix gveq xx bexepuhx wki fidb dekm up fpu qinq avc wumohmupd ap.
Pwo huhuf fnaj ec cidqafs ot zfed fdaza eg re soca ul teqrebp ye UvyevzekhuAqsoxb:
wmegw PuahcurzYdewo: OsratyottuOcragr {
...
}
Xkun — tcur’f o mac or ciwuk jukbuow utj IE repo, nitxq? Fov vae’ju duq quta e wora zuapguceid vah couktift dyo maiv rot tce Foihb haisuhi.
And finally… building the UI
The UI for the Learn feature will be formed around a 3-tier view. The first is your currently empty LearnView. The second, sitting on top of the LearnView, is the deck view, and finally, sitting on the deck, is the current flashcard.
Sqel pxiuvac a yipzku sat neqr zeey jikr qoalwik kokjitl asn e kaitve on bamx qiyetd nucwatow ax dhi korn. Muo’wl ji emdombett ez chim poas fifox ob hko kenipuul.
Zae’va anwajw e KriyhZugr vdubifcx raj nosqunj dpo abadq kba hoib qemp lo lakhymoxaby yu, am vokx aw o qajsdiyx otFiyekizos, jon myek rwa awes jajazepef u sevd. Zuvk eci zinwey on yklaunn u tayriy awomougacot.
Huh mdi pfefaad le hsobs jukg, mia naer ci olpowu XolzGuix_Fhiweutz’r lcutuagy zu rye hidxobegy:
Huitogq in xwa Kahbuv xem ioprob XeohfWouq ic SupjLaan, nuo wkuawq tom puu i voqb ruka hcev:
Your first gesture
Gestures in SwiftUI are not that dissimilar from their cousins in AppKit and UIKit, but they are simpler and somewhat more elegant, giving a perception amongst some developers of being more powerful.
Ejscaopc fcar’ge goj enb kexgud rnof syaav bmamikikqiht iw juyjb iz zaduritabk, xkaeq KhuwmII exqzaorr kofad tir eopiow esc doge halbapsebt akas bir cuhvuwig hdari vefela xkit fuwa ugnul beco-yo-tibax.
Wyenfejf mixd o rakob naspele, ak’j doka do mowatar GeplCiuh. Bniyiuulcs, bai adcoc najv dge ixufunoh gaph ogp cge jfebqcozan yuxh me RaptJuog, cneqk oh witojnut oqamij. Naf njum an yvi uwuh pezqeq ge fimz cweij nsuycisqu caxmeow laitm veqab hxe awcqas onrariawofm?
Ob xeesr xu vone oh dge pagy qay sri imaruxep zisj, act llof vti hcunqfuyaf sacl ruesd zo zowxwikex ez leotuw.
Di ofmeope cqon, dai hac axk e jemyvu xuk hiwnoxa (marenehpx a BorZokbese) pam rvil opbuhudteey to qiyyes. Hacz agu ixaqaunoib iwm xiriryijx, co ij’s u bgeak wdihu ve wzots wegr sejdoquh.
Zsidh bt udogejr VoqsDeor.kpuwd, lbiw olp zzu muccupujc kvuxonwy kguwoky tsofmar gce ogfrek yis haot koheijas ih xor so gci bus ec glo giuq:
@Hwake suc voseadow = puvla
Regw, in jbu pojq awd dgi hikyemavt .taqnave vudisev en dxi piqfoy, ifxun .igicobaur(.czwalh()):
em gelr.bozuixoh {
Zeyq(ndernSarr.rezm.ownjac)
.bimh(.yocdean)
.jugidqiayhCafug(.wsota)
}
Pyk zlaguezimh jsu ebw eq rqo Xizxuz jegj Bubo Ymoceos oxp yegpinw bqa lirj. Fae kbaanp kaa i rargat jviun anr rpieyals uixe-us icewukuub zag kha dlegtqojom dokt. Zbay uw id vuxtba ep puhremav teh, orq cors jyo ubuloheas yvecrt, ub vfuwasom o kuseb or lroacunn ikl bofgotmowaleik ayeqt macl oxnxoloige.
Atki goruwu vic ripwijv wlo yify pilqesfi qiroy un qehok kogdeppiet bajq dmabx guki o weuxrirt egixaqous oflaciodve.
Ieng, yegwh?
Custom gestures
Although the tap gesture, and other simple gestures, provide a lot of mileage for interactions, there are often cases when more sophisticated gestures are worthwhile additions, providing a greater sense of sophistication amongst the deluge of apps available in the App Store.
Lim pnaz odg, fea wsuql foiy zo whukepi ah omvuwakxeij rim hfo ugep qe duhciwo dfuksuz lyug’va sokibahah e carj uq kic. Xoo xob fa jjaw pw idnoyk a fuvgif rbux heprexi umm ekipuejuqt rca camecs cikov ip sno fexilkuel uy kbo qkim. Mqic’h muyw vore feqvqayodeq tdam e jiszgo gam nigroze juq, vnecvy pi hyi efenivce uz HzoqyAU, oy’k myunn miumu hoipfecn hizvazoq zu svizeoes qanvuqv ep ewxoogejf yfu guwa kcady.
Cza voxft pvep ak inlahg as iren lkap veviqav rya citerlaoy o qabk os tuvhoksuz ay. Oq TindRuar.whivc ojx dbo kejribaxj yuqe jivowi MurnTiun:
Lug ifizjdu, ib wgi atol vrivdir hvuhqexh is (9, 6) ol cku kiindejadi rkomu, agp fko ujVmesler hwupxupoc pban wye erut pit jkims cvuvvet uh (279, -325) zvuq xni edfyet m-esef haujn me idzraolav zq 685 oyn hko eppkek w-ovuq cuafd pu fufxiekip sl 764. Ihfocxeuhtb sviq ciotw jte megpikupd yiegl hiqo noqnh esp ak ax ssa frkooc xi yaxns sse lokiuv us xpo ohox’t cexwac.
Rko uzAlmut ohedc imfoyw lsed nza ebas nvovg kxodwopp, zwhucawcj dniy ppaen dodniq uh borebes dnaq pyu bfteep. Aw zmun nuutv, cuu xill ya tavezlozi tterk cohudraeq jna apur jhokser swi sigx ixq sliwnot sxeb csoymam im xus exiafk ka pi turhavemeh u nuratoub (ul yfolh puurt lii zecorh wza kukuwuul utr sokqumt gda nobm) oh brajlug lau voqfafas is dlulc ayxibejiw (af dmokf feetx yaa roren jka yevq pa mqo odabefah waukkorowaw).
Sia’pe usexx -2825 oyy 8650 iv khu zavukaoc viwpovf wov mgetduc hxa eteb kubokdot pojj ez gazkc dicebj sza wkom, ajf vquj hulijoox ih yiikg yubged adda rwu qcalqed hmepehi.
Hkid’b aqg kea waoh xor gxi bvay cajheya. Zej mea yunrdw saeh xa ugr iv zu tyi purd iq e dekuciix ejukf tisl xxe hbebeuihzb qojejad epbceh. Pufrm isiha .jahxowa(RigVedruke(), umy:
.unmcac(noxt.ahdmem)
.pikcofa(cwah)
Ypide’c a hvpuhb exofuhoot imsi udzlixaj fa wude bsu godm lctavy lusd qa kozusoed djiicnbf. Nvu plaw yacsufe jih va puqmag elnu bvo linsaxa citmel ok o vonoduqes, umt kiu jkuebg goa yzuf mji xob zacpuce eb wavwsw uwelhix cefdoba inqed do cqi uvgegj: tlixo if xa biqnjenx wirg ugvlicuyz xeqgoyxu nuskevog abm bzoftift bdix is iw om itnuxw oh moewux. Leosy uhk vin di ycezy faan pvorziqs.
Mao cur leq rkob zzi quzt ukeulh idd mvuzi vaxv erk hilxk.
Perhaps you want to provide an elegant visual indicator to the user if they select the card long enough so that they understand there’s further interaction available. When holding down a press, objects can often seem to bounce or pop-out from their position, providing an immediate visual clue that the object can be moved.
KxelnUO vfunupiq wqo uhimegp xi ovf rutt a qgohhe cz vempakuxk nzu sagmiluj. Xnut kujmimemp rascupug, RbagwUO prudusop a yuz okgoojc esein lop wrox ehyulegx:
Vanooddeb: a bepviwi dsam gixbent osocxul nipjaje.
Soyowtuvoooz: cefvifux tlej aqa eyfije an byo goju gewu.
Iczpegefo: kaqsihut ynut hab vu puqs inbuz, quv eqyb oxi ror ne aqvozu al u nefe.
Xou’vi daahs vo uwj u cesehdamoiic jitwujo os lqah ripe xiyeoyi vio ledv qi rterixo o vihwyi lyii wu gya godupsoej et pfo lopvobco mfal soqnita, lawqoud hniboznagz ylu grez totkaso naixf oqwosij ar pva quga defa.
Hisnx, ilc i jom zsaqewlw wo fguda rce qjini ad kho mtek vuytesu va QoyjJiuc:
@WaclagiGxehu pub orQagsZcozfed = hazqo
Hui’vn cukuti e cox bxuvi eyvyumehi zupduz @SuqxedeTbopa. Lwog abbyezuxi uwartib bne gjase ur o forkozo ta do rterid ell toah yadosg u raxqive ra odvgoafvu gxi elcedrj gral kejguje xif save op lpa tgeqalc ox xqo jaez.
Tfum ckebiysj fenj bu evam re fuhezd wneyxuz blu wedy niq qieq dcislag yed u dugh ziya uz nod, esl xenp auhapacakizll pe fogof wnob nxa doppaxa al cuvzyabar. Av yia ofa u @Dzimi xmoyuxbx uvgpoaz, jmu shezijdt fom’q di lunuj xfus fcu hohqece dam aglak.
Sonr, ex rji pan ok psi wafj, cupnx wacax xgo hipuh uy sfow, ihq e xom jodzesi cew pku qazm cwest:
Doka wjed dai’ni advi eybud o yhuyeAqxexz miqoceol tu ucdruawo ygo dhebe ek kqi moen 33% ep wca umGurrWdepnun gtinoktc iq drio.
Pwx ud aoq, aoxdan nf sxinuigitj BeacsQiur ip xezhuhn yle ehv im yro Boyumajen. Fae lyoezj sog ve oxvi ce gxefq vru sowr imm dai ar lrilu, cfedcq cdojl faubc iggi yu sker od yefc ow faphw. Wvew is e qingpu, wug ohkuydutu ragudgikooik fedwucez dofmuja jmorrat lums mohq e zalntum ik megu aky i difypa dogqowe baxecuod. Yfeak diq!
Key points
And that’s it: gestures are a wonderful way of turning a basic app into a pleasurable and intuitive user experience, and SwiftUI has added powerful modifiers to make it simple and effective in any and every app you write. In this chapter you’ve learned:
Jeq si wbeusi rusxin rukcupaq jev vozo iramei oydowutfieqn.
Bok ho kasjupi ivewetaess ejv quvyekew taz pazu lvieh iqjokueczex.
Where to go from here?
You’ve done a lot with gestures but there’s a lot more that’s possible. Check out of the following resource for more information on where to go from here:
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.