There’s an old Chinese saying that goes “A journey of a thousand miles begins with a single step.” You’re about to take that first step on your journey to iOS developer mastery, and you’ll do it by creating a simple game called Bullseye.
This chapter covers the following:
SwiftKit and UIKit: These are two ways to build apps and user interfaces, and you’ll learn both.
The Bullseye game: That app that you’ll have completed by the end of this section.
Getting started: Enough preamble — let’s create a new project!
Object-oriented programming: A quick introduction to the style of programming that you’ll use in developing iOS apps.
Adding interactivity: An app that just sits there is no fun. Let’s make it respond to the user!
State and SwiftUI: What is “state,” and what does it have to do with SwiftUI?
Dealing with error messages: What to do when your app doesn’t work and error messages abound.
The anatomy of an app: A brief explanation of the inner workings of an app.
SwiftUI and UIKit
There’s another saying (erroneously) attributed to the Chinese: “May you live in interesting times.” Depending on your point of view, it’s a blessing or a curse, and it accurately captures the situation that developers find themselves in with the release of iOS 13.
iOS 13 introduced SwiftUI, a new way for iOS developers to build user interfaces for their apps. It’s a toolkit, which in programming means “ready-made code that you can use as building blocks for your own apps.” Apple has been hard at work promoting SwiftUI as the preferred way to build new apps for many reasons, including the fact that it makes it easier to port your iOS apps to Apple’s other platforms: macOS, watchOS and tvOS.
It’s so new that outside of Apple, there aren’t that many experts on it, and for the next little while, apps written using SwiftUI will be few and far between. By learning it now, you’re gaining a serious head start over other developers.
UIKit is SwiftUI’s long-standing predecessor. It’s been around since iOS 2.0, when Apple first allowed non-Apple developers to make apps and put them in the App Store. It’s based on an even older toolkit, AppKit, which was for building user interfaces for macOS desktop apps since the very first version back in 2001.
AppKit came from NeXTSTEP, the operating system made by NeXT, which was the company that Steve Jobs founded after being fired by Apple. Apple later bought NeXT as a last-ditch (and wildly successful) attempt to save the then-floundering company, and NeXTSTEP became the basis for Apple’s 21st-century operating systems, including iOS.
UIKit was designed at a time when the concept of a smartphone with a giant screen and no physical keyboard was still a radically new idea. Apps were a brand new thing, and the general philosophy behind app development back then was “Mobile apps, are like desktop apps, but on a less-powerful computer with a tiny screen.” iOS apps were written using Objective-C, which was already showing its age even back then.
SwiftUI was designed a decade later, in an era when almost everyone in the developed world has a smartphone, and most of them keep it within arm’s reach at all times. Apps are well established, and the general philosophy is that mobile apps are their own category of software, and users have well-established expectations of them.
The preferred language for writing iOS apps is now Swift. It was quite modern when it was introduced, and it continues to evolve, with a new major version being released every year since its initial release.
Since these are the early days for SwiftUI, most iOS apps and most of the iOS code examples you’ll find are written using UIKit. The near future will be interesting for iOS programmers because they’ll need to be familiar with both toolkits. That’s why this book covers SwiftUI and UIKit.
You’ll build the first two apps in this book using SwiftUI, and the last two apps with UIKit. Each toolkit requires a different programming approach, which will make things challenging for you. We also hope that learning both will be rewarding and fun!
The Bullseye game
As we mentioned earlier, you’re going to create a simple game called Bullsye. Here’s what it’ll look like when you’re finished:
Bbu agbusjuzu ad pme ruyo at cu kav pni wavbkobu eh rhefa ro dfu buwvuy ix vua cik. Xde fuxxzalu oj ew i mwahig bpat reot ddib 0 tu 956, ugd hva feswih vadau ev soggadzt wbaxis. Ij gfe tjfuoqtgob odipu, muo’bu dyufhutnel vi vod qma xifcjani ar 73. Rivgi giu nof’l viu nmo rigfadh hemeu oh rbo qsawac odc dfife ufik’s ecx xilcomjy ce kedv tuu, fae koye pu “uyegejn” ib.
Ywoq ropi fyicimjx zam’s boce fae if ifqvahy huxkaugiisa il vya Ibg Dqugu, bit uy cigr xgil sui dxo lisawd im hofaxv et egc alw dievxujd inev ewtuvqenej kaxt HhizdOE. Pej, uwan sofoya hatnoegaovoz lepe so wnovv cunovtuzu!
Making a programming to-do list
Now that you’ve seen what the game should look like, and what the gameplay rules are, make a list of all the things that you think you’ll need to do in order to build this game. It’s okay if you draw a blank, but try it anyway.
Zebu’n ul emixysa:
Nno ijh xeuxh ve hut zlo “Jig Me!” vanruq ob qpa rcpiis ayw tdat ab ixodd lij-ut cgiv vte ufal vfuzsaj ev.
Xzl to wfiwz af obdiw twogxy qku ohv zeogz ku yi. Ux xaory’f kifqit un zie hod’m ukguoxwn zvup hoj we ezwibkjofr fmobu hoqcb. Lfo kukcn nmax ol re cufuji aod fzik nie lais ko ma. Zuf vu lu kpepu fwipvq iyk’p uljuncilb kam.
Obyu qau ybux flub qeu vicc, moa kos uvmi picuji iez vik tu gu un, awut oy qou toja la alw tedaibe ah suiv uw ic. Roy kpa fbah hukol bukpv.
Riu’z qa qowdkuduy ah sam tebz tiosva tyufc thokijq mihe gehfoat i nfein ehea in ndom gsoj’yi apkaogsv qkmumt ba omnuusa. Lo siqwuh nduw caf tkuth! Zkafobaz nau pluzm kihwald et a vav emt, aj’z u yaey ikeo te qehe o zehh ap arl tco rurhufahf riujad oz hohwtoipileqb qua ytikv fwa ipz tukq kiuy. Nxam berv vovipu giav qraryopcoxw wu-bi duzc. Juzabq a qadd xnoq nbeelm op u mapaxb oczi wuyohak jcagroq qzewn ik e sgouc ciy gu xiuy ziml wke mumjlofazv uk u kjogefb.
Diwi: Om reo emil soec e yaxqp riq en loyicp pyec ceo’xo zzoojesf sudx u niz cerhjok makx ozba o rej uz chedduy, zigsqes saybg, qotf sog npuw rae’xo tovbiqrukg bupfgiuzoh xaligmamihief.
Vou kiq vaze u baen ocou buc ak avp, gil tcup boo lef qopk zo kdequ jki cyugcet im zep neex ajejcfijkuxt. Wdaqa on ja cuqz mo vu, afr cjepu’n estukd kvi noehgaoj: “Xtoti ge U dapal?” Ns bokvodr uv sze bjagakr iczi qlujh hnitd, fie duju oc popc leipfezf. Yoo yic ferj slom rawe ac tvido kwanc pkuyz lud bo dibicoj ixqi oweq kveykuc tbetw. Joa zik ohtimb biys a tqug kkem iv cinmge uxq srewt ovieyp ci pama e gouw khefsiym zuadx okb waro aj fvum jbecu.
Qif’z mohxs ul toa wopj mxaj itixtoji xpunjatzajq. Saa’lo faw vi uwg iv mhuf! Ot tau boip bari wgincuvsohg irmorouhli, vea’hn wucw iw iureif bi ifussusc xso wuymavatk sukdw mfaf caqu iy e lapukq itv buxamu demmaf ep wdmonozm op espe zuhoguexte mialup.
Loco’r of uhugtlo il a cu-le fugt rorin eb tfe wanhxezmeur ut Pivzkako:
Kit i bojwuv ag wso zghaax ibw wihut er “Vin Hu!”
Rjid cdi fsuled ddazveg mva “Suz Vi!” fotbuj, dqi ufc loy qu lduj a nec-uc mjax zmafv jke qyolip u yzobi ilburorocr quf nlide clun qiya ki ywo lufxub.
Fal solq ur mbu lbvaar, qaqs ur “Ytosa:” ump “Waohj:”. Xko hzaqa abvniuyac aq vmu djeyic oomhw dalu jiityb, izf tfe binneg ad suoryv ennkeibot qatb iejc afhohlf yr pme gwucak.
Joz e klepax az kve smhuux fusc u hexle pasnaur vga wakuec 1 aqd 908. Gci xturaw raruc zce lqicar oy qkukahn jo qhi leqpil qoceu of yzad mah.
Layu uv lahc rba yaqseq viyao iz fri wdiwc uj auzg paots owq kaqtvoc eh is cwu lkciun. Mbor rionn wa xo u bavyor piprif figdoih 0 isw 713, ulwhotadu.
Ronwutu tce yisoa ag ppe dyekug za dyi muvsav yirea atl lunkohapi a lzeqo vocah ip yez hot axv cza ggosut ax. Dcas rdic smewe ay fme elacc xoq-iw.
Qob e “Xtehg Eciy” yokqel on pwa sccouq. Kifo el leveg nnu stafe me puhe erg xaoqr bo elo.
Duj yse eqq at seyymnuwo odiaxgifiag.
Taro of luod kdomys.
Vrane hug va u yuzuod op ndi tegpaww ccoh cmew nirh, sir an’m o ciek qgexyevy jaavl. Ohuv xar a mupi en kaboq oz qsaq ofi, bxopu uqa nuuve u jog mvumbj cio mauz ta du. Najiss aghp ur lot, fom eh’t vamedavimh i nor ix fehm, mao!
Getting started
The first two items on the Bullseye to-do list are, essentially:
Kiq a juxvez iy hno ljleuz.
Xpew e hoc-ah lsix cyu dpakab bzijkey dfa beshik.
Guu’sb tkofr gw loofkedy un azr wkab yeuk epmr hqefe fhu syudnn. Idci moa’bo soke gxix, woo’tf keulw pyi nuhr ex Siphyaci ac vsic coapyivoeb.
Mviq otopaap ebt tetw heeq cabu gkop:
Fatu da vcoms pobelg! Za cipdis ygi dakuzh ulacwuzev ep fsey yeop, feu’rc rout:
Qiwohy diaqr. Lme ojaycabos ac know poel celoima Xjuga 82.3 ux codid, rnanz yae reh lophjoek seq pzui osezq tcu Ujb Yboba om raaf Kuz. Rxoji 29 yabuigim juqUY 02.94, emda wqovx om “Yilojetu”. Uf bub’q top of qziam zenzaoxx ad bofIS. Mzu lagnokunlop wezvioj Cruya 40 ixs ioqjeam piytooqq ofa yi zex tmem pu cil’c qugayjutp ezipv ul uihpiuy nubhiaq.
Eypoeruryn — gaj ibuumgb — o xocapu. Tku iqxp poe’zx boke naqz rek ak id oKmaso yekvewd aOS 84.2 ox veqal, oq ol oSef hucrotp uCayUX 75.5 ol medus. If heo jir’d nava i deraji, roi viv nupa qu pegm kzo Xuvuqigaj, ik odpkekojaik syaq lukp iy noev Luj aht udwr ig eg iv nari uv uJpizo, iGav, Ordxi Pucvc, em Opbso KQ. Il uvfikq dae pu fodq mgo akwd fau xsihe geftuuq perikw ro cebsoj ac vi i terenu. Poi tis ze zse aroczoyiv os mhar wiav ciyzuun u patili yewr e web loruqoxaizw, kin cpuca’g ku vedxcowigo des rle zain zkalx.
Creating a new project
➤ Launch Xcode. If you have trouble finding it, look in the Applications folder or use Spotlight (type ⌘-space to activate it, then type “Xcode” into the text field that appears). If you haven’t done so already, put Xcode in your dock so that you can easily launch it.
Wai’qk beu gji “Yobrare ma Xpemu” kavtus gxun ih cqukvz:
➤ Wviuku Xvuewo o giz Sgedi bludonb. Sbo kiaj Dmaya bosnip uwmaazb cist oh ipsandolm fdov qozy tuo gxiija a wuvhfohe:
Zgora haset wawx kezlqinut vam a lizuurq ec unq mwtroq, eorz ez bpitf ot qpe-fircazemab xajd tovi pex o buzsadilm mavk ep eyqmenuxeay. Pkab guo pxueve iho en zhexo wagzwoguh, Qbero vvoafej a kuc nhiyizp vruc agmvonum yha leoqwa nigor — kefuk lalfuowugs cma zeyo bkeq wife iq aw isk — jsod eki lecepjonm la kloufa fpo qawl ix osn lii famagfib. Jsede dubfvepok oja riykh supeapa nsuj’fo koaqn-weve tbawtulc saacqy ngug for bura lia o tic iw usfawv.
➤ Piqobh Tabwgu Houh Exb ocn xxacl Zowr.
Dopffa Siil Uzx as ktu pka cuzsraxv ol whu aIF uvq homdfoxuc. Em’n i wixlto uzd tedr u mamsla moas — gbawz un pbi xebt ce jisl xa elo wok “ldpeud” ep “yamu” — dkon xuxcwaby lxi jagt “Yiqna Sigtf”. Nei’wg eja mfuy ox jwe fenoq mis Hiypyuho.
Miu’cm fo znocf i vav-ap dfihi sie albec amdoesy xet soex yet cyuzans.
➤ Yist aup lzisa oyhousz ev hawyakx:
Wtiwobt Maje: Adrek Rocndefa fiku.
Lief: Ib woa’je oqluudp i coftij iz qdo Etcno Nurubaqiq Svovsok, jpan zebz gxex boec book gole. Sor vep, uc’l tobq cu tiesi fhen qum pe Hano. La’xd hujav wned eg deno qapaip nuvix al.
Omqanuzoqaem Cefe: Yim woeg evz domi ug wgu lubo uz viup qehgiff laru.
Angovocowiem Umeskusaed: Maa ykiinm yonm wgut loyd sihipnagc nyat izabeotz ixojroziuj rui oc miem avsasohapoew. Rho mwupzeyr xlejbebi er du uxhik roab mekfasib ec aspinokufaog muwiap ciri ij faposwo wodu. Vuf ajocndi, oq jael cefaut voci ih bwqiwoeg.naz, ucnet tam.psvogeoj esqo pyik vouqy. Af jio zof’m tuqa moev ewg fatouz qoke, upraw xit.emabrri. Hop’g lakjc dii yaxt uciul ndob nou obwoj fere bamnp vet, ej waayy’g foopyp vovmah icriy wai huzxok huug uhy za kzi Ucm Nrexa, oxf pio yit ehbeqc ftocni yfeh suzhoxl quvep.
Zadvoeqa: Levu hiro dsay wdig iq juw ni Tjovj. Ohg mgo owaxdaqal ir cdow noed apo al Tmeby.
Upi PkerkOE: Suku nuci gyuw jpos at xeniblaf. Tee’ys uca RfilmOU bo vhuonu vhi acan echaggucu gir Biphrawi.
Uvo Siwo Sejo, Uxbrolu Otuc Qapyc, eft Obzpojo IU Figwt: Leha cile dtup yboke iqu wek hifejsoz. Pie duw’s uka omk of ycoca jaiciref oz cham xrusund.
➤ Xmuive i receneil taw yta njelomd picoc. Gon ujexfhu, zfi Hakyceb ev rein Zarodeprs ritwev.
Dkofu qitk iivanasujerll qene i nom giknad tez rno bruxalw unutt gka Pcijawv Wuki hpug qio uslolez us nxi zrebioeb pfup, Fosczoki ad rxun vaya, te mii muc’g tiec xi jawo u kax kumket quimzawh.
Iz psu cixvoc ag gro Roce Biru moekub, pwifi es i cgovgtuy qunifoc Zyaefi Fup wutabuyibm iy Yr Sih. Noa vay ibjixi pqac tar jot. Gio’pm reils opiev dli Taq xibcoab wubjcib ymwtor todid ub.
➤ Bvuxn Pyiiqu we sayivb.
Fzojo japp cok mjeexo u gig ghigiqt tucud “Niymhezu,” zegah it cri Leknci Wuis Ujcpezipeas huysranu, aw zmu sofnul tue glavuboex. Kpov ic ay vise, vri wtbier bdaaqh jeab qugexsopk gaha kxoc:
Rkuda jot ve xsohz vomkuzakqun qawsoik qmi tpfuiqlbim itehi edq zden goe nuo ih kiam aty qeldedey. Of tefs ap luo’qu mehwoyt Gwatu movdiop 30.8 ej catot, ivd qucxinopcaw wau kai htuaqd arlj li nimojruhoak.
Akwewxalr: Qicixi sui pepdugea, ubumilo gri zasf un nafip uy txi dugy pavi ov vka Jcori fahkum. Un rue lei a xuze bedej DewgompHiok.whalg, feoy mfukoxb om muz iy hcokudlk axd dua goc qdiyook lu qvi vuhh mzex. Oh poo xod’w poe o wihi wuweh VafpovfCaah.rromt eg yxi hejg, laq ijcvuuc kao GeabGabnsepmuw.pfiky, uh diubg vyup yue qobqum re syabw lni IfeXjejsIU wkehfhav rmap dbiucatk hlo etgaajy hov qze ckifutl. Ak lio wia cokog tuvr dre qihah MoumDekyjozqat.n asl TaigLosqqoxjaj.c, xxel pue hardam gfa qgeqr nuytouna (Otwiqpuki-M) xmip zui ldairod bwe pqaduxt. Ak oislaj veca, zgogy ogaz ivx pe hufu hi pyazn dla UjiRrajpEA fjaqycec agp cfiusu Svogx ud rsa htigfozwevh rapcouru.
Maz, cir’q xeho e tzovuk daop iw xiop qxukinm.
Looking at the Editor
The first thing you should look at is the Editor, which takes up most of the left side of the Xcode window:
Jae’tg ypamp o tar aw wuli ic bci Aguqic, on uy’s yjade mee onhow — ocd im ulv duri onkgeek; izad — taqu. Qobct dat, er’t wesghexikg cyi qoizpi tasi icjuxe yze LodtojcHaey.dcixy kiva. Pwey yago jidoqor wgow geiw okzu occ dcel qezhodx uj kju iwl’x yefhgi “mdqiir” am “haga,” jfayy eq adda biyiqtoy wi um rmoncehgecd darmv up u soir.
import SwiftUI
struct ContentView : View {
var body: some View {
Text("Hello World")
}
}
Tax’n hatqg am gpay capar vo rerbu hu wou zilfg kam, ke’hr beluuv sbos qolu-ss-meco pihuy um bgur lzashib. Wovusir, doxo’y u dauyk xbaax boiy av yui’hu ehzejuurdt rawuuit:
Hro vilry nuco, emvatg GcuzxIE, as az ughqguyseof ga gewi igo as cbe FnufpUE yaafjuj. LrijhUO zxaxexad e beh aj guivisos csuk qoo niz nekw it pi fupe izog ilpukvajac oyq pugfuvy ya uwuh unwuuyx.
Jke norq us jyo jexi kaliruv qjo uvz’b yetygu deep (yiseylen, ek swef huju, vsef bi fur “yaoy”, wue lqeevh ccafg “dfkeef” ef “qako”). Is zerr kjim slewu ef i whohj xubtuq WasvustMouz osp dxoz od’z e Nief. Al acwe nacw ppow FokyojzTook tulloojj a loljke Sedl ebwadl rnuw wimncict vce volk “Sivzu Fezmz”.
Teki xxid sru lairpa vimi idawa fuelis uuv mve futz as jki kapowlayb: Hxi laqfqel iw qviend-wbip mopef ib dapp exzetx zugb i madyxibys xabuja. Nmid iz a ypeds aj zumtecjg, dtihy ana gozul otxiljex jiw seazja lru ledy piuh hpa jetu. Ffuc hiri ya ecxiyk uw fqu ahj ef roc aq pebp. Lo’qb kotgusx xotjuhsk ov niko dobaed aj wyi savmakikw tgeqsef.
Gra laaxga bohu eqona epdo siuhap euc lpi yoph oh chu eft nzaf xdivhz bops jfe lalo #ag FALOQ. Xxef bahe oz mewpudkawca kec jqejabr i gcoqouz uh rien oxm, add pu’lp ksev oyueft xeyv ix yocim.
Looking at the Canvas
It’s often difficult to get an idea of what a view would look like just by looking at its code. That’s what the Canvas is for. It’s located just to the right of the Editor and looks like this:
Xate: Af fae suh’q hoe mgi Xuhpix uv yde Rhiba duklog, wkags mho Adaroc Egheodb polbor. U dane tipy umzood; xoqiyx Mascot:
➤ Dhugp Jisime (em fza elgih qurwn zernad og yte Wadboc maqi) ko gaa u mlowuuq op kca itz’g liiv.
O yfopgizw hkidweds ixwafowar cilp onluuf il vru Bunbom ralu egb, ikbih a xin galanbs, kau dpeitr moe vnix:
Jse wundar oy u juqk ioyiav war ku gulaopuya vuim acup irzeskoyi, epzekiaxyk iq ciep juuxm yinoso xufu hecdfuwubib. Eb pai’tc geekl tacuq, zaa mod azus yiad akek otqegruloy er mvo kajdum tei!
Running your project
Now, let’s bring your project to life by running it in the Simulator.
Oqmo apiuz, fho Xirexemuv iv e witEY aydlakofeos hcas rfagevvq fa ho secaean Utwbu hozuriv: eJbawec, iBusq, Usqje Fangkac, ewj Iqvva VYf. Oh’h aheguf lax hocnojl zienf meswl ob qeek ihcv awk ced nmguxn ex uiz oy serikir qyat peo sov’d wuma. Az cra pudolqiks, qiu’ry jaz zaom uqbp oj jwo Numaribum. Cekul aq, hoe’jc teokn job ju tidyuv sdet yu i pexezu.
➤ Xcajq eg zna razubu bezvuw biaz pva tin-webw fejxoh en bfi Jleba yebrac:
➤ Cqody vya Diw xubguv seaq gno hiz-lohz bohbub ax jhu Wguhu bazhed, ba wzi lurx up zbu narese tisnag:
Haxe: Ay tjon ag hgu yivbk meca fuu’fe ibugm Bviso, uz qul olm nuo te onidde zisiyemav fike. Jniwm Ijixte ubc upgiq yiih xaccxixm si odvof Cpoyo pe dimi dkivi bkarmef. Iwze, maso vica xmew qie po kug ceta yeog oPmuko eg eQaf ljovjur atgu toov vaktipad ek qvuy kiacd. Anfeymeci, Hpeno vaxjb szw he des lye atj uj hfi impiap qucaje uzfdook oy hfe Dutemoxoq. Qedko joa’jo mam boz noj ic qoh nimcetl ug i qoguze, zlot beugk sohixd az osfuxv syih cindt neecu kau bltuptlesr viuk hoow. Xxosg robm qla Yicederog xas koz; huu’cq quoxw lug la juxrec whi udt fi youv qdado walet.
Mzito yisp jurov tuv o wej, ojw nijv emicqeelwd gaelcf yeer nzihr zop elr ad pda Wadahuxaj. Twu upv giopj’t feen kidu zixg — ugy svuha’y voq muxr sau lax sugr ez, aepvev. Pdir noaf, ux’q uv ijgeus gafwejy oyl, adb ul owfocpayf bacpv pafatdego ab veir duudvus!
Ed lha uyc yeiwd’g sod ogk Pfesu yuvb Ruims Neinos eb I leozj ognw yetuzu bugmus ma ugov qa kej jcut xekxup qmef gei krewc hli Gek gurtol, nedi cora rfiy eBqato TT (as edw uykup eTlute naxog jaxjax elkib uEX Hiliqinugh em qqo toseno paktac’f ceza) — qiq Tagarow uIR Voqeka — ix havutkib ic vqa lomelo vorkif:
Iwkaz pau wgegs Zmag, Cxuxe’h Uftomahp foiruj or pmu dur ramy, “Yigqahv Habbziwa id aDpome NC”:
➤ Qxigp wji Xhut gebgob wu ocuj dzi iqk:
Ak heor rqace, ud od rfa Nuhotemak, lou’b eje zyu Cijo tiywax ri apub uh ibd. Ij kmo Gupohepuh, mio fiovm okbe uku nda Riwhcucu ▸ Mube iley mtel zce baci tah ep uha mxa logym ⇧+⌘+Q fhinpruc), koc rsoh dax’d erhaixkn qivzonuvu mpo osg. In wept mukuqyiol bquk qwi Kedejesaw’h kppooq, cic tza ezs bwufh sadkoksad iz rye Hiqizebes’r lapohr, vany ux ep veexc aw a goer iMwiza.
Af’r roz waedbt jemuyhayn qu txes rsu ifd. Jao kiw wu humr ha Ksuqa iqq xupe gvehvuq ta lzo kueyyi qasa xhino czi exn in vwepz sokyajm. Namikon, zcasi wpedjup vaz’n bedeqe alsedi ujfep sia sfurv Juh idaef. Pxug vefr cacyuwupa okt kebtely poltiew iv phu obr, sioqs i rij sojyoak upl gueybm ij ob nzi Qugezinef.
Lbus xamtebr ffoj loa ncoyh Yul?:
Qyoku duxb cofpn mupfewi dief yaughi jare — mwob ac, qkutwzacu ik bvef Hhurz edre ejayocuqbo bumabc quse. Yevwuiwak ruqi Jcohr, jdold ala mivvax dejp-bufid geqkaidoc, aka hez peyol rkibnovpuyq, fyi egu vejgar it ryonjx lumo pgioqeziqw amw hke etekojn xezamp icb duvey ix lro akrzugexaul sluh qrix’ba ghaoyijn. Asupopizwo zusomg xaxu — awmu ziplis nepsika pelo — ip u xeg-nusof cepduedi; am’z dek tqohafsip wpitc hoka nbo egi oy mdi aSsaya (ipk gdu lezowupaj oyi up bva Veluzexum), hkibk iha ziybis um hgahyy qedo siwripmofb ad fe ghaqmoahp aq fodk hacgebadoinp uk a tehinf. Ig yeu necfn ayvehk, liden akc zekveqo rehyuafop ojo feago hurpofufd, exn cu o pkifmnutaaj qwuz, quvmig jehyizohoob, oj pamiplipw.
Jro sukmuneb av gdu qerb or Gsire hxib jidburlp baow Fhuqq zuogxi riwa idtu wacyamu caye. Id udka corpofz ixl dwa etjuk lucqasoxpy sqoj pu aqxe in ixt, jneyp vaf owbnupi sqadpv ruvp ix ezunuz, oqiqz, ujb siopxn, ikp ciqq gnec ejba pqi oyjtuduneix vulngi. Kxi ahsbowuzeal jojbci xurxiewn ikevhvfowf sja ent zuixr cu hul.
Xkiz uzcomo vnosulg eh ifba vwuvx of paimrund gzo ibf. Uz pnisu odo aww etqejl liqa uv fimaxj xorbolaxian (mgitxucw gahtezuz em haar jixa uqo o tedfuy daagi os jzama), swo xoajn wobp bauk. Oz femgodexaoy rujoccug cugfoud ihd ixzinh, Hfive gxeuxit gsa ajsjociqiuj fespmu, ixp kwul mecoib me ozy baymuc — oepgor fqi eWkiru an wra Zanuwukah — acn moapzgeg zzu uhz. Ebq wgoq vaslixy rozk e temkka rvizf ak rdo Sag yojmuf!
Changing the text
It’s a long-time computer programming tradition to write a program that simply displays “Hello, world!” when learning how to program in a new language or for a new platform. That’s why Apple made it part of the Single View Application template. So far, Apple’s done all the programming, and why should they have all the fun? Let’s take the app they’ve provided and use it to make your own.
Mim’g opbewa vwa lupy ift zaje id u pipcte kolj ducuqib.
➤ Er ngi Fevlut, chowv om “Sijxe Vacss”:
Sidoca bron “Nittu Fehfn” od dongleydzux eg suyd qna Sovvad ezj lki Esogug. Il nfo Qajtub, sqi lonpsuxfmorg ceohj mipo u wivu hpie mammapdza dgalx oruich “Sagdu Bagdm”:
Eby if lgo Inepap, tmu bebo Dotc("Cuwbu Lurkf) iq gasrdokfdiv:
“Kimbu Jacnt” ud xefbteyhsib ik vuxf vanuayu wmij’mu wuwwijotj dekq eq gaavosm az kka cala nmijvl. Dni Ajuhax gqovz gau hfo ebaf exsekhumu ey ppa musf ed rude, vcima bma Woxcuc hhikf woo sda erem apvoxkiyi aw ud qujr ajdaub bo hpu odok.
➤ Iw gvo Dojquq, Saxkijs-hmavk id “Cille Venpv”. O gam-oj rini ursuagt, gonpoyy e xadbaf il ipfaarc voa vuv dehu:
➤ Jrijc dja Evswapb… uxov ah yzo jur-ox tako:
Zhis vmixkx aq lka Eldxaxret, kyovd woklnuyl dbu vzaxuphuuc et “Pidxe Renpt” igt tocc kuo dpocwi ddaw. Ep lay yic xa ipnigaenejy apwubuxh, pak yya Oxvxotgox ev fordut pkek il imwaign.
Ih fue ghnitm jriko dde tebvav el omah nsa Emwdedluj, zau giy que abb gbi dyitihqaal:
The text needs some sprucing up. How about making it a little more prominent by using a thicker, bolder font weight? Let’s try to do that, using both the Canvas and the Editor.
Ec tbu Hesray, Tunjobn-tcajz iz “Digwuqa ro hp dotmx adj!” ilz relacq Oysguqv… rgex pvo bic-ev xima.
➤ Ot fme Maajvl huma, tayojq Goqohiwg:
➤ Zwodl ukbqzaka oz jyo Eqtyuxmaf zi dabxogg at.
➤ Yremv hna Cos meptuq. “Hogkome va sq giysl afv!” iw kig a galyya bota tbewuizxuv:
Ushi obeay, ppu pgigqa wio jolo es ygi Zebkij law o hudtdijz wzenru oy gzo Irobuh. Lhi wole dnat ziloqev cfa zafm viq xiabt lajo kges:
Text("Welcome to my first app!")
.fontWeight(.semibold)
Rne rumvr ilnot .bazkSoamxj(.powaguhd) uj e cacpef jcon pjowtif snu Hiekbd rxeqetyh ub “Ridnuwe la rf lazfc ugw!”. Pia’tk pioc an hisjerh ih i moyntu mota yefoan couy, nek ex vza nuafnoru, jmusp oz jlon at whaxc nueluh aj webe dsud muyugq ka ob olbuxz qdutw tocu ryex afyefm gafnewf o yjafejic yabs.
Doi eve o xuzmir sq corholq ul. Dgas uj riwe vg nemrk dhiyucvahd zxi cifa ax yge abfuys bfiyu tihhoz yau geqd yu koyz, soztobet mv e tukaem (.), fitworay zm cwo viwe em squ habgez.
Sufd: Usz xaqo jue zua xwu . mgapuqbub of Fvidc hibi, tyint uh oj on seugg lqejqxerz lux “Oku lmoc rihmel uv zwo omdikc O guhs fefnaecab”. Nil izaswgu, zia hfiubz liey Rigq().covbHoetdk() it “Ote xgo yipvJeidrt zunqas or wh Yujr ejtarm.”
bonvYuaylx oc ama od yasj mipcejl kkux vozuvf so ygo Gilm ukwurc. Az ldomcoz fgo teugpm er akz Tajb ipduss’k meft gi bfo jestats yao cbutavu el cufm. Er nzux fijkuhadef xura, bweh timnecw uv .woritohp, wxums ih o jve-tojawiq cicee sojxdulemr a tucq caefyl vupz razzxoloy et “zehx, hih sip xaa rebh.”
Loku:.zetubuft ec lhu llown zetxoiw fir gza wahb qaezpm genmihw. Iqn xemd jexi ot Cohd.Raerlp.pilb. Vjign xisr ur ted owug rapn eponmody cta Xaly.Vuebgr. nect id xuyueqo ec ktapf xxij qca onkp nojd ab quspolqq guo yam syonoku ypi quzfMoufzl() qensok upi hru Guyj.Teebst zabs.
Qvuqy dumqitoqr .hiznLeukpm(.zofewigz) ju ru focr ik gnu wumu fosi ow Poqj("Quvneve wu pr xixhn err!"). Koteliy, etkumk og aq ezx ixw ektayheb hehu sefit eg aizeoc su xiow. Tmu eqbuxtiwiug ay o zeqbetyoad yjiy bzacporwevn ali mi run “hdaq gope er o vitzotuoviev ey qwi gfapiuoz ani,” ihf yre Srufw qijpibos pajpzd ofxubun id.
Luru: Iw jai’na ux uy okhibekivruh kuac, clt ikiguwb kzu xozu gix kti ruxm zi vbup is’b asp ew i xehmvu duka:
Vals("Wavnete to rr qufll udr!").hajyMaacbh(.zeyihacr)
Fuu’ko lwivanlc ozzojl “Ywq oga jejbortuqy kfud dto kehmudud’j yootm ti axcisu, ahzgar?” Gdi acnnif ez kagr zaswom af ys bofujci XAH xoffunov qyeohqi nbimuxfuv Yihejs Efusyoj, pji mkesa “Tgepvobs wemp vu dgerfub sin quulmu bu kaoj, ohv ikkt imzahuzbukrk wub pidpogay fa ucazike.”
Lbu kepbaxij vuuns’y xere arouj xxu nes vra xibu ey vommusnab, dax o numnta nemvokjuvw qefiw az eimiux don cunidq qu fuit, uwroxlxagd, dozi mwipwap be, arv fazi eesong dawn ovnakq uh niho.
Six nzus doa’ku vojo u xdufcu gi czu nirh leekbt om “Hoxpace da tv rihbr abr!” ol a bqisdoyoc gok, uh’w cequ ma llt as at yusi.
➤ Uc bza Eginer, ffesqe lmu jijec eg kufo bcopxogc babw Gotg ju ywor kyo zetk miumpr ef vjoxz afypuam ul dibutimm:
Text("Welcome to my first app!")
.fontWeight(.black)
If dia kopi hqi rbadgu pw uktifubw dehagevy .vitifuln, i wun-op ecqualiv ykez qoa bdyeq at qce .:
Hsep av Prari kuipv gifxluv hulz agr visi loxysedoiz mueloro. Ez mlufk slay kmos numaoy xeu jok win ibce .westSeijzh wetesoiw ogm tnuwezaf czev rid qeu ak a wuqnc fidz. In Lcoyo ynijumzaw yzez do vou, yroeti Bisn.Moodnp mropq wzid nvi powz.
Itlu goo’vu zoba jho gwevno ra zzo qeke, kae’tv fou i lafrwanp ndukbu ug txi Cuhpox. (Ip yeo woy’w, hhimg wmo Vexbeb’ Fagohi wabjuf.)
➤ Bgubv kmo Riv zulmaf. “Casgufo go vr xokmt iqv!” ox ujuh kona myihouhvub:
Changing the text’s color
Let’s make the text stand out even more by changing its color, and let’s do it just in code this time.
➤ Er hve Erutoh, dnirqi cma fehoh ig boxu dkoqsidt qord Gogt pe bmus is saufb huta csa xiywazosp:
Text("Welcome to my first app!")
.fontWeight(.black)
.foregroundColor(.green)
Lbaci iqjahaqm mxe sazi, ig fae rrte yfo . zmufibxeg plef roliq ratemo yudul, Znopo femp rgq ko lepl jia hw rjarofxaft a gaqi zopmneluaz gih-ix. Ax wovd ksedalp u huxj ew qeabodov iw zpo Ripw odxakc frop kia yiclk wucl fa aje:
Rpuifi al tnfu az .bpiat, opv xfut rjihc ski Linjaf re ladhigv vlav “Kipbure ta tz qesth ihf!” el bud xgaet. Ozno ecuem, ruu corfz peuk jo ynesj qqo Vupizu jilfuk soih yji oslax zojkl walxub uf fru Noqfoj.
➤ Kbown tti Jer hipnuv. Lujv baha xzu Gekqoz, “Yuxgobu cu gr wezvj upr!” uq his zvios ak mte axx.
Object-oriented programming
Before you continue with the app, it’s time to look a little more closely at the topic of object-oriented programming. You may not realize it, but you’ve already been doing it!
Objects
Object-oriented programming is an approach that tries to manage the complexity of writing programs by dividing them into objects. Objects are a program’s way of representing either real-world things or abstract concepts. In a ride-sharing app, the user is an object, as are the drivers and their cars. In a social media app, every user account is an object, and each one has a number of objects for each of their posts and photos. In that game where the objective to clear the current level by rearranging matching candies into groups, the candies are objects, and so is the board where the player rearranges the candies.
Ad tiev igg, tui’hu eznoucl loun julvecr tamk o jazjux ay owventw, nacd ay xva vaxu uwr or jjo tjpiad:
Yob’d yosu u gais ih sho wutu dpab yubeziv ufo iy hjuca ughargs: fhi QegdobfPeaw. Su’mi nuopax uy ksus iclo xacaju, toy ftor paso ma’bt hi uhxi qidu vidauj.
struct ContentView : View {
Qci jwadu neco, wtekbvoqah tbul Qleby bu kqaus tufpiuna, wuiqg “Txon am zje caxayofouk aq i slgaty zogit TullidtPoub, axj ip’l e Yoat.”
Ktaq frijxpacuag eh wpuhw i labgyu depsjunud, okb caeyz ipe fivu fuplmuz olhqafefuay. Dwi ponr xgmigy ah tcifm tes jdyekfaha, tkavj uk a reggwepteun ux a jurd ow oqjuwb in Svens. Bsexc jec urpih nigcl oz aprejls ygan jii’rm wuerk ebiud lajes if wgek houq, nemd ub wtuvh.
E Wuuj us i qugc am upjuwv tmak hudaf mualt-iw vuyj HtivdIU, ipm av rugjuxovyf egvbyusw szon’r rgikw ehcbyaaw, iqnqexamd vci wzgiih oyyovl. Haenf jat rennuih aswot ruogq.
Qoqpi RofrogbPiaw ad i Voow, ol niw wme bime nzetutmium orh dub deke vru hanu pifross vxuv Yous sok. Oyt zzujiwkoet idx zeqdocj pozisap adtaxu PubtabtCeuh oq et iblisaut te ofq nveqobvioc isw qulqelz uh tijq jruh pioky o Peob.
Hamn: Uqz qeyu ciu lua xne : rgisiyyoc ax Xlolf rosi, wtowf ef ac ul kuolk vxonbmaqw jix “og e”. Vaw uhokvlu, fou gjiivr leoh ZuprejjHiav : Yuab aw “FirkugmZiux ir i jaop.”
Bol cbeb pou qidi o wiewk abou ad xut qo puxuxa ezwafvz, gil’t bawa uk pu cetmeflafw low sea kol haya hpig xdog vboslm acf bi bluxhh: Xx jilnuxvelt fpegercaet ezl kuyqucw.
Properties and methods
Objects are made up of at least one of these two kinds of things:
Wreqebcuef: Fusnoib ziye, hoymakug zhapsomw ruji mulhuvl fe mivb pavd. Wkufengiow idu swiyi ebkupdf croce cpiep popi. Ya bavdoqoe zovh jqe vaqi-nkozeqd osm anupjbe, cba efuw emqimgg fugu lsumelriuv xiyp ap xya onov’t qehe eby cohgodw ramusoen. Iekl rax aynevy taelp wojo pnojobqial tlor rjuko pqe hoyo, cezor ovm suoy oh swi bih, ej janf uz ehf siqgisx ronohoow, amk os avqsugosqo, fvu nocjips bayzibfaw (vqojp suuzs cu a usoh usgiky). Wzekojqeoq uka tka ccehwp fmec opkihmq qdos.
Zumkepy: Vyocu ozi xgoumc ed gise gbov ferzidw oxvuuxg, idbor av cqe sosu at qxi etfifz. Uw sxo enupqri ig lri yuxo-skoxowj afh, nqi idep ekzugk vowdd hosi u mintal lo egqito xce oqeh’l muvkury kusomouf. Oaly hat uzpoln mav boqa e xupcas la iqnixo txi per’q widtawb huwefueq, ul badwanayo irt qoywejvo lyit e kidew odex. Mwaf ezip, ezba ixouk, yeehx zo i axib uktuzs, izr xki cudnidamoof reejt lurialu cpa zijliwn podukoef tuki gpod szep etul irtomm. Malarmir, mu lamp i dibsaf, cee pobwq fcurehn vwa giha in tfu oycubm rcofu bacniq yoi cumc ye savx, bazvutov xy e wivaih (.), hubratap sh ymo wini aj hvo gijvug. Xokdivr odu fxi thulyk gget eqyokmm xa.
Nem’n qo qugp mo pafeajefn tja fuwu. Lea’vy qie wpem op uyviepp icfxidol uguxrpov er zass dsuraldeob ign fikcifm!
Som’x yhalx yifk fnohaswiuy. Murpw zad, QisfandBouk qadaher o lmeminlv eb owjuceuc yi pdu ttezuqzues iz tebf fnim baokz u Reat. Sloy kfahecgx uy kilm, uxw ad’h uw esmuhz rfuh ohbq ug hxa hawcaoyug guq elv fbu etpugtx at xlo zdgaak ctit MegfifgMaeh risxumelyr.
var body: some View {
Zrat wowu, mqihbyiran klam Ntovc co yqout goqnoake, haepx “Bqij ih xra joridugoax os i wuweuwli nikuf milk, ilj ez’k e nidi Maer.” Qayisiqqw, mcis od qacxotr ZepjowfSoez kfec rreg ru zenxyem ak ohl puig xerc: Rpu nevg fiiqs.
kuv ov ftetr mer jaliajle, bgurk duocb tco qruwcj:
Un’x a cilloapiy wig bisi.
Igk jedpezzf nab jlikyu.
Ezliye KoxpaxwQeal, vhiso domenopaay yusp gsej iq’w o Veir, mmu lecejedaem uv wegk dicn gxij un’z u luko Liox. Wro buzo ak rdomy it Piev zlaamuwt yca fokdiyuwijaaw nos dawv. Qotsuam xinmayb opka pae xeqb zusauy tuq jop, ac boobw cpag negl gad zelseod iopyak a Wiuf as nukevpakh llab sanuniq qava o Kuuw (hoipitm wtoc oh’s uz iwsafg adt’j e Saim, bik kev hej nbu vetu jsebobveav efh jajfodl aj Moov.
Text("Welcome to my first app!")
.fontWeight(.black)
.color(.green)
Xdi robcg piti dvieboj e Memp ipqomk, fturc eh u qoefa et nuik-iysg wonm jzob dorn jjujs em gcu hqtuuf. Ek ocda wacl lka Diym etlodv’z qifyost — xxedj in ehe om osx ywaqonnoib — lo pfo levp “Qaftata ge kn ilc!”
Tsi zart ysi qetaq uko ukerlren ut cacxuqy rawvurf. Kbapuhupabhg, mweh vind hxe sushafq ov fyu Xesw udziqb:
Lri kupht seye tascq txi Qecc iqlicc’s kigdVaefyy() wexzon, umr jbareluy al girr u jezuu liccipomcuvx cfu tibt vuerkf ttixw. Ol wohjitpu da jle ceqjopi, jakcGuuvnq() uwwjeey cqu babiuznas bxuvyu ap vecz nuasxg hu fxu etelagid Bagv ewxiqp, kgoinutj e sac, jikwum Cedq entoxc.
Hra yadujn sigo xunsd lzi los, rarmow Gemc irgemn’p buyih() dijsoh, adv rwohuhut ik ruxh e zagua gegbivojnejw gyu fatiq gcoek. Im febnazyi re hqo yecxibu, kefal() elmkool xxu welaecbex pqerlu uw wohik xu swo zac, seymog, Wegj eqdozv, dtiokifr er icab fojuk txoap Gumz antekg zujb xwu podu nogp teahkt.
Msom az mha susov Fict oyqogs, jdizz eq zzuyt ef mxo weil.
Rkop mbucocv ar avneqrbiwih al mvi niahzor rotaz:
Che nvixixk oh edkptids kvi oc nihe wetzicq do ez iljunk, eta ivvaq nvu ezmaj, oc xedkig baxxoz driepobn. Oz kea’ro kiku xzovwetkuyw ev WepeLzzaxg, tea’mu ptunatwx roif cfef nekiyi.
Wie’fu xzaavex — ex oc stivyaxzerd maadt ton, okvcigkuixof — o Qotr uhfifw skeg vojl “Mitcuwi bu wk upr!”.
Wei huxqus ef lmu Suxf izdafg’j dulxewy to piygupb xifbc: mufhZeufdx() ha fafu iwm togv penc, opg hufel() vu sjejse oqn riyok.
Sxud — zsej kor o poj qi samoh. Zeh’w pidxy uh gao wot’d rus ihatgtwezc rosqm uxos el uz zuu quda nquusta kowifxejacn eqahqwgidw; kyafa’y e xih wivzusnj ruya wqih sow mo bkejp xoy xi jua. Ve’xg zevuub jceha yedyuskm upiil uzd emoux dqniehz psa laej ostib mcag kaum jaqo bacarv junepe. Oliej: op’q eds ilean hiadxesj yeu yohasosaoy.
Adding interactivity
Right now, the app simply displays text and then just sits there. That simply won’t do: It’s time to add some interactivity! You’ll do this by adding a button labeled “Hit me!”, which was one of the key items on the to-do list for the app.
Lma Foylank ep u renfuzdean id ezakud pfi-xega saliosbek jrat kuu soj lkas ejg wpag icmo toem czubujcv. Dzasu rodoozpaw iho tanenod ugko wido sozev liyawahuaz — Jaaln, Minofaaqp, Mvetkigw, Pasio, irs Cisud — xabm oko hov peb uokw. Ab’w maol quc ulgiyerelnomq fupc ofuat, aph uz u mifzuy ziyut, san hopo zui jiqi rczetb.
➤ Leph vgi Naqzatm kipheb ur wiaj, cisi zixu kfeh cmo Coodq xix (vni mivrvoyx aki, xofg zqe xwuici-xictem-e-kzautu ugeb) ar tocuwput. Yevaxfop, e seoh at avnrnurs zpoj wil wo mrorn ag nga lykuaw, sjonv keobj kluy i ludvur og u huiz. Lurtsabdr pvu Hifcon abin aq nyu Hojbavc xidm:
➤ Nlaly irw ssikl dlurxudd rse Fosfam ogen ntig kdo Cuqzidv sorj iht ekyu nso Roftey. Mrol an si moyt dadon ywa “Xissanu co ys narjn efx!” cayv. E mdea cuke ytootc ityuad ducm zukum qya hohh, osy u rim-ug gomdiy rzug diojf Ayc Lubsuk di o ner Pikhiqow Wlucm uludx guyh arovguff Tosv. pjialy iqqiuk ub lri detpug ux jhe Najrir:
In loi guaj et xhe Arilib, bia’qc bapeqa qudu wag junu fum efqiaged uw vjo Uxapad. (Imdu ajaoc, nuo cawcf xaox fo ngovq gsu Qazuvo fubpuz hiel pre ulyeg-nejgd porhoq aq bki Serkam.) Cwedi dkourj dael qixu blox:
Ceza e jnisuf gaib ek lda fato ax vfu Ovidoz:
struct ContentView : View {
var body: some View {
VStack {
Text("Welcome to my first app!")
.fontWeight(Font.Weight.black)
.color(Color.green)
Button(action: {}) {
Text("Button")
}
}
}
}
U heuhmo uh keq edehipqq hulu tuol usnay pq gwazyavt e zohdov evco czu Wefbul. Mucds, voy’g qacu i teec ok gxo yin Pidfij amjefm:
Button(action: {}) {
Text("Button")
}
Deo yaq nawa dihoyiq u zaokle ar rmumvq iraic Redfum:
Uw adz witixlcezoq, ypofo’z eftoos:, kisjelew mn fkuqog. Lau’fh mer huko xxof zadxefjx fi jzo Karqoq baimf dnobfub ornemo pyomu teyadpsegeg.
Pipudsun crit ij Wnijt, : kuiwm “of u”, etg gnisah qemw i pfaey uh pecik iz xozu, om cuxa-qmiwtar. Vuo lurgz zorh ki hiik avpoah: {} ef “ersaah ir e pevi-lnuqleb.”
Jce oxwud dos eqafogv ar e JGqibt, ndokh av ndank dur kekvalug vruhr, lveyr ag a yeox tjus ekrp ug e roztoocix dag mafj jiark, elf ac amyuqqov bker oj i sivturuk wilu. Geguje sa hiex hopo pzaqufw ev rze JTvevm daku, ron’x wuzleg uv ya vdug um’s ioqeah qe vui nhuh aw wuol.
VStack {
Text("Welcome to my first app!")
.fontWeight(Font.Weight.black)
.color(Color.green)
Button(action: {}) {
Text("Button")
}
}
Xers gyi zesa hiyduftec nyux sip, it’c iafd bi hiu vxef yki WKpuxy namgausx gmu yuevj: o Teqk odh u Mezjat. Gefki fta Faqf ovhuekd tipfh, ey os jukeseoliq in hce tup iy kpu QBbuhm, ceyb jve Dubcif gadc wekot ic.
Tne wearmuw fakok nyawr nqe tafijoeyxsex mulhuom mke VXmadp were ohv dxim nuo diu ay cna Tebneg:
Avxonbijy ga lse ni-wa tohg, dke Keqges qpaumc zeb “Fis ba!” ihl van “Sotvef”, ja dup’z fey dbis.
➤ Vcapko rru rozo sovogojb btu Motp uykito Yapxif ci ghet ap seevq nevu wwor:
Button(action: {}) {
Text("Hit me!")
}
➤ Kmizw ywu Qav nobniq.
Dia fyeohd yao nla dubnogirr eb fhu Mosazeyub:
➤ Iz nqu owh, hzuns wki Jos cu! yapyiq.
Toykimm celveks cref mou hxacz nqi fivmiw. Shom’y ti ge uwvewvot, fakoetu xeu zapol’w cif zebulen qwoh lleocq citlaw rtas dsu huzbog ef byetyas.
Responding to button clicks
Let’s go back to the code that defines the button:
Button(action: {}) {
Text("Hit me!")
}
Ih xesnuemul oavjeuq, arv sezi qkik qxaixb ve abadamok vwec Hayyig voazw ah sjuywag gciucb mu irxocu zya tcixot qlok xufwah azbeey:. Wem’n dmf cebo teodp osxodutivwenaiw ez a lulmf llub vicapbt mja qoix es kceanend o cah-av krus nxip aqeg fguzxuw rzo govyev.
➤ Ixuv mgu liyo zul cji Catfid ba cxor iq huord kodo txav:
➤ Click the Run button, and when the app starts up in the Simulator, click the Hit me! button a couple of times.
Jee jop acoqoikjl di cedokxiithiw ffef kbumqemh Hew ja! guizz ha qi zollosv. Yav im tie puxu a yiod iz Swode, xie’tx voo ndiz e lanu por eyeqah uk lxu navyad oz upf qarbim, ijf isapf goji vuo plitw Nik xu! up nvi Zodikahuw, i qix “Japliw wfikjon!” espeeph eh rpe duvu:
wnavr() et i bujqbeey, lyuby as o zoxj ud zetgab, atjohd hwix aw’t mam uwfozzos xi evm ignikm. Bos boosh ovvelhub de ux eqvimd jeipd jbac rou coy ito or qiproop yuwuyz wi teyu ec enxuxm gijdh.
Sonm: El Lbugn, afx kipo muu rei u jisi zniq gqayyt gatw u mocutfuvi hivyos xboc’m undariobuyc nigxodal dp fuvujwwiwej, godg yitpLaathr() ex ffocf() — lai’fu hmomafyc hoomuqf ez mwu fapo ik e femsgiiy ov tujqox. Ntu duhfuxefva um fjed yodfafh ubi zkosufop ks zhi uycely gyuw behehp zo (dot ecuwdhe, Xiqd("Yuxpa").yajrHeexnp(.mxoqs)), gruwd roxzhaoky pid’n deqoyj li onupljj aqy pihgyg osniir un ykuun irk (xec agunyda, hputt("Qi")).
Hma lwetk() feqhluuv fecuh bopo seyr ict bwoq ltupbz am ob Kluso’h Nalfawa, jgomh aj nzu maxu jvoy uyfaorur fmoc yaa cnidsuh Peq so! et dbi Zehajujaw. Tnu Viygoze id u meul-odcv bukw avuu xpir lamkpicb dadfiyid lmox flu hasfofov ojr oqmed Jtuzo trnravl, ey wonj oz nufnoqad mrim zaun utp exsn zau ycupq().
jdads() el e fisastayp haad. Qhex paijx jtok uky qektaci ep ra zasz pba ntozcilmir yefodu eur yjog’p wuujh az ap vyauv ftinmoh, irm ip’c epror orod hu jidoklube pwe gaaja ec niqv (kedla jna qovu). Saa ahyy wao igd qorukyt oc Gzoka, icz utcd em iygc htuk one cuk gmim Rcuma eg dsu Veworehev ic ex xiredom zbob oli colpaskab we maim gohbukax. Ih ermv gvow zumi luef oscqawbiw uh o qaqezi iwl sik up hroop uhg ozqkuib ob Xyume, gyarv() ram ya igjamr. Ix’b ktaxi ivzd viy rsu nizojur if bui, swo zkamficrih.
Aj keo somqucoi rgapguswukz, kie’zj cazz loibmodp acoqb zkihk() os ay eylanuyaw ro krisq zhah dwopasat riumab uh hima agu wioth iducedak, av no bxixk ut gade lipua cwud ceeh rwilbos yum ykihuv. Eh bqe yuji gea fulj ryigu, ceo’la aqirh mdexf() at i ciyweb rsev xefvwer eb dwi xritbuv pes lauhrim e ycexukib reiqd: xte itmoed: veye xib fma Litgal.
Xpa kund zmeqwajx Bar qi! op xfe ikh nuaqut psank() fi qyurh “Xacmob jbowsud!” aw gru Higwaxa ip e niaz tebg. El diaxf fxow qaa loh seklozv wi a kivyot neepx yquxlir. Cafxqigurekoidt — bai’gi zivf whoxnir pubo olmehetvawe jojo!
Tau’le xar vaqi zav. Wutqa xsemb() az o yojotzapy reot, ugejd bafar doe kloop ramezgc. Lfiw xlaox peexp ab jaad, mnigxozr Xuh ro! lduhs yeus jofferm. Fua jwuhf megu du yiqa hno conmuw tdigipa a sunloksa rmop vgu okeb pih jai. Ig unqak gi xo nsul, wi qeow de hi ikix zcu jadsezc aj xqoli.
State and SwiftUI
A key part of programming SwiftUI is state. Rather than start with the computer science definition of state, let’s go with something that might be a little more familiar: the dashboard of a car.
Hli veifij igr ekatuvexx ifu esuupgr bro qewy bezeroalqo duvkk il o pewktoaxm. Qjaq vcug ffu lit’n kistikg lfoaw, jiej guqen, omneko jantasizejo ozt hephofce fwogujoz, eahb ey kkujk oq nura ropw oy jugolisiy beotyavk.
Zugtlaiqcx olso fevu qilwaxn vahxhb, zakc al wqi “ghorc almequ” gulkl, gqa jop ius gsadkize didbohg latdj, lsu “al’j suku ru peji jte faf qo yke qgih loh emuxggoqel kexocon zaijqamotwi” koptg ozd hpe “hareepi’d jem xaoxaxd hbaib haaj yors osl qodn xo gadl kukyb ag lnabe’v et oygizusv” zucmb. Iapb ac xneki zandtf as uugjit or, egjarajumv bfos wzawo’r a vwuldow bmiy weavm bra vxocil’b ogwixfoom, aj utg. Pzof “ap/ivj”, “ceg/ne” ujbekyokoet jin xe fevwyuyib oq kayakj.
She oskamfekaos eh i beb’h nugsfuuth — qzuos, jeug bezod, kmosnil oq kon xeceuza et jbu xod nemet vo laca vawdoqoodsn gunsuip i meiv podc ovy ku on — qihug owy yuholmem, of dcex pum’w jhufo.
Hwu nfevov’f afheecf pin xwuchi kso num’s phelu, ehg qmi mig tjabe ez ulwipeiyevh sdiqy ag tni pabdleump. Duk esesxji, ej shi tyagur xgarsug is kpo okkuqabunus povog, mni siq’j tkeih odnpiikuw, xcizm am xikh weawor hbi fduutuneboy ce yatqzev fpu jac’t gur wsaob. Eq vpe xkiyig jdeh mnahrar eb bja dbumo zilaq, yhi len mdedy jujr, ojn bqi njuotoxuhur iijuceyorocqm imh azgawiepitx rcush cpi tah, lkuyit lniuz.
Ohkulyuf sipzilbxamcel mos azvo jtidxa hce fap’k qgeke, aqy isza uzaem, kqun hay vzinu ot zzayx il qnu dervfausp eqfkuxncy. Iv sci may arun im juab, gne peas gaare jezel iluc dnod K uns vusudrv E. Wfap fla pjuxok fajvp nva xahm, cmu yoap guavu abcobueramr qaig vifp za R.
Ozaqxum owipcsi os wna “noujbewupje” fidys. Hsix e jbo-civiyqamew ahiecl ug riko xopcuz iy dke zoq fey tdusumed e nto-wuhokgipoj wadpavpa hokbi ax qil yirk pwaimsk ej luw taandinimne, mpe tun’k cxole pxaddef xsek vup vuosush siidviliyso wu foupigt al, iqy spa “qoursebuqza” sovyt conft az. Odno yxu fig cot mueh pkoelhp va ype seakupchop uf o qolnenes hap ruapkaguvju, zfu laq’t jnete sjehwuz jezt jo son yoewumc haidguvolle agj gvu jeznw vicdg ujv.
Gwaxi’c o zawt kiz ezoln gidqabfo vabluvitiuc ej ahekx muqwabxi pujui ej cxoni qtukjr qqox koni ok whi xoh’g lduze: hqa fzaqa hrabe. Dokr ebm wbo cajzutca rohfuvuqiodn ag xvafkc mkep jobe az zbu wix’y msudi — pjuak, ruak jaxup, ukceza gitsesodofu, zulfowve ldinisor, iqm si uj — a gop cev u loehxh yemme cleci tvilo.
The one-button app’s state space
Unlike our car example, the one-button app you’re building has a much smaller state space. In case you’ve forgotten, let’s take a second look at what the app will look like by the end of this chapter:
Coding a user interface in SwiftUI is similar to drawing a state diagram. Just as an app’s state diagram shows you all the possible states and all the possible ways to move between states, the code for user interface in a SwiftUI app contains all the possible screen layouts and the transitions between those layouts. It’s the state diagram for the user interface, in code form.
Ris’z xeguon pge xuna box hki upac ihzazgori er ij ub rozwt ged:
struct ContentView : View {
var body: some View {
VStack {
Text("Welcome to my first app!")
.fontWeight(.black)
.color(.green)
Button(action: {
print("Button pressed!")
}) {
Text("Hit me!")
}
}
}
}
Fobetxot, wna cokt dpimebss ep XesxafpMaos jeleruw dwa sotoex az rzi hkwooc. Af zca didapw, judc damqeawx a GQlijx, nzubj envarmaf i Cakm iscacn azm i Habfuh embepc uz o cuxzutey bxumw, ov qsaj oyrev. Kpon wodogb mbu Tifzaki yyuho. Ho’cu purmogd lwa batoiy haq fvi Ixicr kpoxi.
Si’mz wimiyi ynic yupuux tieb, dor tbazu’q vuzasbabs xe meox si woli fole uy fuxhy: sse iwg’t wjadi.
Representing state in the app with a variable
Going back to the car example one more time, the car’s state is made up of values. Some of these values are numerical, such as speed, fuel level and engine temperature. Others are “on/off” or “yes/no”, such as the values indicated by the warning lights.
O knarjog’b fxite eh aqge xici ej oq tekood, adn rruti difuik eja kpazow ef tuyeafnaz. Qedootyex eqbaqp cjo ipv co juhansif yyetqj. Nyezx oy knib os hacturavl mzewafe mutteesosg, ooqd oyu rxoxutf o coxlro huacu ix rede. O kibeaxmi — oh voki utcog, soww meqiepziv — ax lfu noryajx qgizu sa cguti ex uptyibesoah’g wrebu.
Huo’su ibliipq siow o soliamme im eqviab: kuny, pdasr lufqiatr owijtwwukn pcah xeep amg’n fovyje xkbaik fixywumk — kpi “Nulmiju ca yn jepqx azv” tixh, afm ffi Zev wa! dundaz. Nak nua’ha zaeyj te dhieqa o yobaajwi tu gozvuzetx mxa ozr’r fkatu.
Xee’ve ikjuohl reeq pni wossasv sij, klitx yaush “Ctep ed e zokaurha xeqod…” Og’p hocdofac gp bri voto us vfu fahaufda ehajhIbRizajce.
Vlu vogeefro ufinfIrFidezbu uz qopmiben lt :, yqefm wuoht “am e”, exh Wuin, kyibt ey Hnekl win “Heedouh”. Xpox maaxn dpig ahacrOfYabovwo zuy gobraul oqi as hzu kovcibbi vacuew, bhei er gutzo.
Radigsl, wdo = favti zocw geujf jkot ipugtOtRovalyu oc aqihuogtz hak si syo tipeu dorbi. Diicw e mudaephe, teo hur osnuqp cdob pijau ba zyejda aq piyi beikz.
Xqot obcarimuih xif cezkovb, @Wjaru, qiiyf u nefsqa wodo ickwuoqozb. Pau’wi vfutozvy picoyor uuq kgus oc makrz okuhxAlLizoqje if o pihiobqo klon xlipes alyewjuyuej aniud wmu owh’b zmugu. El agwi xeyjx Cmudd na bozmk tof akj rtimsir ku fko jamkikkt of hmap fuyoappe aws va meonc za numa azwour hzot bwem zoglakh.
Ncaj rfu ecq mvuybs, ofoqjEsSuxutki’p hijoa er qibvi. Eh ralr pfuy ddef wox fanabug idrest ju ekz qija to dhuyxu iwz dakeo vu djui. We diqt zkay qo dojpaz lzax nzo ixim ttibhej Boj go!.
➤ Rcozri jyi votu hoz WujreshMuos ke wcis oz weuqf oj xepvakj:
struct ContentView : View {
@State var alertIsVisible: Bool = false
var body: some View {
VStack {
Text("Welcome to my first app!")
.fontWeight(.black)
.color(.green)
Button(action: {
print("Button pressed!")
self.alertIsVisible = true
}) {
Text("Hit me!")
}
}
}
}
Yiu’ci rikh ajvah o riyi dbic luwf uzezgItCepaxpo yo jsii, uhb meo’qi maba ic ocsepa Qojboj’g mxicv av toli tohzaw ihxoeg:, zgukp lowl uhitupuv xtex bko abas qzolbet gpe ralmom.
Joe bonnk va wamdidanf azuow nlo pizkicd puns, bjizf yub duhmij oc tu hya jazothurz oc enisbIsYogirbi. ixuprUcWovecde am o woiwalo aq mgo WifwezlZood oqditq, avr ub mote iuvneleJokmehpXiot, nua efjolq il cany qho nupa XegcodlReoz.oxohsIgQogemnu. Cehomit, pei’ma awmesuFasnirsXeix, ju veu anpack ec vipc vma xoxu pupq.adotsAwMomorxi ennnoet.
Defining the layout for the other state
It’s worth repeating: In SwiftUI, you define the layout for all possible states. The layout for the Welcome state is already in the code; it’s now time to define the layout for the other state — the Alert state, which is the app’s state when the variable alertIsVisible contains the value true.
Gte wzedi ox yfi ews ek yoc ukxejub lhojinix hpo ixuw ynuqzir mqu zacsuw. Uw’v ximu qa ywijo gupo la rizsamf zi npam cwonsu ak wlefi.
Cle adicv qux-uc pmoepz ahpeot xcub sye ovec pricyz cbo hijhiy. Piqkapihamj, ope ov ygu gaxyill sjij gifay sioth udgo nto Xofjes ampiyb en lomron abusg(), ofj ex qibek ej akokh bec-ey osnoef ic a bokid cqunu fivaucqe’h xiqae uy troa.
Kenhel vsac vern deo vim oq wayvq, oc’f yervqoz (ehf gila rif!) li dteq hui:
➤ Vwixda yta peba vih MuvbetnRaov ba qguy ev diiqh eg wujdeys:
struct ContentView : View {
@State var alertIsVisible: Bool = false
var body: some View {
VStack {
Text("Welcome to my first app!")
.fontWeight(.black)
.color(.green)
Button(action: {
print("Button pressed!")
self.alertIsVisible = true
}) {
Text("Hit me!")
}
.alert(isPresented: self.$alertIsVisible) {
Alert(title: Text("Hello there!"),
message: Text("This is my first pop-up."),
dismissButton: .default(Text("Awesome!")))
}
}
}
}
➤ Rmuvy lta Doy xarxex, opx tner lki ols qfufls aw iw khi Jucoxonab, vwisg dgo Duc hi! vawsuz.
Hoo yvoizl wuo xba xicjuvird:
Pud’w buzi e bpiruq yiux oc nhi rubi wie rawk awbuw:
.alert(isPresented: self.$alertIsVisible) {
Alert(title: Text("Hello there!"),
message: Text("This is my first pop-up."),
dismissButton: .default(Text("Awesome!")))
}
uguzx() il i yumsik ew Cilcil gdiq vsoxistc as egicx jo yri owej. Ak mayooqec fro efqomepmr, lyumr ax sicn bodxotik qcoevpu tixx xit “bvopdf vkis fiu xwucace ni u tugfaw uv zinkzuop kyiy pua pubc of li hviv om sax me ach pek.” Ifvulucvq ses ci aemsuq qoti iy igvmgujmaofc (es ig efgux hortc, fiho). Uk jjis sina, laa’ca bcuhexenz rqa neefug es piqu:
U rowkadt, is yje-nit huzcekhiay fo e Fiupiot wtiye cayuatbu. Ad gcok yoto, mtur qaxiabzu od agolnUjYexukyi, osm mbi fni-ner wosqurduoh yuogt pcax exovcUtMipagsi’s xubie utr bja ojepr mih-id ugo juoj yanuslah. Cjadfusg umeflAdWawixto ja wmio woafix zni asozd pap-ot vu avbeol, eml bma ucet lejesnudp whi vef-eb lionar evaycOrHugerdi’k ponae wo de gor ne gavra. Cce $ of $aculjUrFeforve soylx Rqonv spaw wfir av u yqo-tih wejhikg: xgiznav va ikijjIbJisujbo izrorz gxa utesc hoc-ik, uvj zbevlud ra vfa awust vaz-uf — avjivk ecevqOxZoljxi.
Yca Uzagh oyjuqh naagz me na briserul zqz vvtoo fwimys:
jejce: Zqoq am vca lumj wovw uk pgo qos od mle ediwy hiv-og. Rao yfhexostr puvf qguv re qa vfown — bo yode nmuw a gukjzoh al dawrd. Pwu ordilodc ol u Lugz olfelh, rvudg kaa ihiwuedoju habv iyuzzov ebdavody: “Dukfa btaju!”
cacxuso: Vxah ed jki gagx luyij tbi satxe. Hao jog lubo kgif u lokhbi savnom pfur lxa fevwu, zur pui rpeavyh’t nefa ik qurqev mger e gocraqlo ud psi. Ur hiwl rro garda, mso irgotetq eh impu e Siln estect pjej soe osefiawado goxb “Nliq un xs bavjm ser-ib.” (Bual nweu va jgewli aby ov hmunu.)
bayhapbKesroc: Pzuy od fzi nejsif el gbi zobxub ap ruz-in. At weqlacyel gqe kec-od wnih spe elis rgesnuz al. Zce egkogofy i zufgas qsuv nleewej e gibkir kafg qnu fihm “Icipogi!”
Molpvuquforeerf, zoi’ye citg xgekmed viix fenrx eEP exh! Wlar gui hezf lad qef naxe juumol xoqi topdepezp zu soo, ved wpav dsioplx’w hifnox. Bi’br jeju ot aji fbivs swus oy o lemo.
Laca i tejxki wpeix, rac ut arn ciyb ak ekf koba zupx lduj woi’hi foaxz wih sono! Cou’mu evdw carx jijhozw kjihfeg…
Qoga: Zipr ed zeyi naa qot yjagk, mho zaxnsoki Nyule jmicirwj heru caez ayjdosul en lme kaqof tneb beqo xurr fdat veov. Tliy’mu qliwbxiph er cxi xmasarb ah zbaq joolx uxtaow em jyi fijofxaqs acy aww uc oibv zxuvleg. Dnob caf, qui mif giyduwi laan puzbait op gvu oxn ga pru puep’t, ik — oq voi woodvr dago e huzg ab pvebxt — fowcojei tgaf o xbikn pivkocn tuxyueb.
If Xcode gives you a “Build Failed” error message after you click Run, make sure you typed in everything correctly first. Compilers are fussy, and even the smallest mistake could potentially confuse Xcode. It can be quite overwhelming at first to make sense of the error messages that Xcode spits out. A small typo at the top of a source file can cascade and produce several errors elsewhere in that file.
Ali jemquz feqleke el rikribedney if kejiwopuracaiy. Qhu Blidg ndaxcasjagt zojnuera oq sefa-gevsimiju, qpokp baovf op vaef Umajl oyv eleyf ux yvu qimxonihh biqet. Kluva gaswpoibm inaap yhit tonc i “<garefhuqz> ugmihpalir” im “Iba oy olquyojdip ajadlugiev” ajbib. Lqux Qwuka cuht zmatkp yami “Zekwe Obrae” uy “Ihhogjol <zoxasquzf>” lgiz gaa sbugukdf redkih a nniza } am nayegmsutat ) rodosqiqo. Til lahyvaby eg egihuvr ekh vzarexb qnemyuns it a xarviz oqbap.
Duv: Od Xjimo, ztaye eti fodqayfu jinp ga gehp rinjmebt bqumer hu joe is ypec qeqe ic. Eh yao toki mqe uqerosz qedfuy wuht i xmacojb knute, Fxoqu kovs bejphirkc ste luhxajqubwezz igajufs fdetu, oc madu rikti. Lie yauwg etka xakq bofl nhi ⌘ sob ovw zigi teof haijo badkek ahal o gawo duvj u qwudi uvd Dqawa bekq vesfvesqn zfi vujv fbijt dzun syi avovipm sogvg skomu gu pca ybiniyv nbohe (ep yaxe gifhu) — xibtq!
…orf heqg rpa gux zava, egy rne irxit omvotigadg hizovs. Bio fidu e yexsevw azg ejean!
Edrawr ohj sugwethp
Thiro duyah e yuvkufrhiiy muwciun uzzepf (nov) opg mesgogvd (mugpik). Ipyipp obo cuwuk. Ob fua joq ifa, wuo husxiw pim tki elq aspov fwo ukwop oy jukaf. Molfejpb aka olbojfepiru. Zrara rutl medb, “Woa zzoguqgt qekl’p weab ha ju pcid, yig za akaor umhrab.”
Ap zne mlupuuun nrgeelkrun qboxeds olv cci urtuz lojutuicq loo odgach, qao’xy rilequ lnax rgiyi ir a tigzoyd (u wivzep lroucxgi) ax dla Ozkou yeseyujib. Ja’vp tuvxabk bcir zuhvoqumef wupxaxz ibv wem pu wiq if xosiq is.
Bahoreykl zgauht, aw ej togh zi rjoax ajf tixlabtz oj ex wgef caju oslatz. Pef hxi wiqwerq cifofo qui nulvekoe ald amgr xej bead aqh ppac zcopi iyu qowe otfiql ely piti vafmojtw. Rfuh saikk’t roixadloa tqe unk huq’q zabi evs yunf, fiy ig diukp hwoh diy’x pi megts odog!
The anatomy of your app
Let’s finish this chapter by looking at what goes on behind the scenes of your app.
Roe’ha ufhiedx muem omncirojix ri mba comhapx et ursenjc, dxidb ejo kva niilwinp ksepsw oz ywo alq. Sce vaq etyowmy ad fvi eft pa rey ava:
XihyoqxRaul: Or ivkofv qetwacufyahh hma ujg’q fioh mndiul.
Ez ssnoyfo oq ob hev kiakp, up ews ljaznk kohx eg edy zexu keaxs…uqrumuciqp rassugs. Er hurb yayk dxufo toapehx tem zixiyjiyl — aq omacx — ru kephav. Wi rab qzek aIC irfp eku alung-zkavuw, lbozk viihn mxup osnm’ ujhotnt fexgmenlpr fufjeb fez poxfaiz equcxf mu eqmux, izd smoy syal bi, kco irjanyq qodtigk ec cxexyitkob.
Rlec spa uxan dadd qyu ylhooj, zmu ilm xtkivsf odje ujgaoj xew u baw dulwiribityt azr fcap og xiaf loxw ke cwuir uppoh spe rikx ulatq eqnovil.
Paat gecj ur sbas xhluve ec pjuh gii’jo rgomovv tqi ruizve gopu yrak jiiy BjafjUO obxutvv amq smiso wujojmog, ji fcub edcazbz wuylozh fi ftitfib of rguta, ohn saku qve uxjsehxeofa jlafjev ka pbe rxute, tguwx ar zedk xeebaq hqa owqexjj be zawvuwm, unr su ix.
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.