You’ve built two apps with SwiftUI and by now you should have a good grasp of this framework. SwiftUI is great since it makes it really easy to define your app’s interface. However, you can’t call yourself an iOS developer without knowing the basics - our good old friend UIKit.
UIKit is an alternative way to build the UI of your app. It has been around since the first iOS and is currently powering all of the existing apps in the App Store. Actually, it’s the foundation on which SwiftUI is built.
The best way to learn UIKit and understand the differences between it and SwiftUI is to rebuild an app you already built, so you can compare the development process and the final outcome.
In this section you’ll build the Bullseye game again, this time with UIKit.
This chapter covers the following:
The Bullseye game: A reminder of the game you already built in Section 1.
The one-button app: Creating a simple one-button app in which the button can take an action based on a tap on the button.
The anatomy of an app: A brief explanation as to the inner-workings of an app.
The Bullseye game
As a reminder, this is what the Bullseye game will look like when you’re finished:
The finished Bullseye game
As you probably remember, the objective of the game is to put the bullseye, which is on a slider that goes from 1 to 100, as close to a randomly chosen target value as you can. In the screenshot above, the aim is to put the bullseye at 84. Because you can’t see the current value of the slider, you’ll have to “eyeball” it.
When you’re confident of your estimate, you press the “Hit Me!” button and a pop-up will tell you what your score is. The closer to the target value you are, the more points you score. After you dismiss the alert pop-up, a new round begins with a new random target. The game repeats until the player presses the “Start Over” button, which resets the score to 0.
Making a programming to-do list
Just like in Section 1, you’ll follow this to-do list to get the job done:
Vaj o xuqvan uv ryu kvfair itt dixoy ex “Zex Pu!”
Bjec qzo hkisoq whumzaf vla Qor Ja! cayrav, cjo ewj vaw be prah am atoyt jic-as za ilbuhp qra dhabak yux kihp lo ij wbe dob. Vuyoyal, sea xoha la fefpejofo kwa dyaqa uyx cuy xbax ulco hwev ogisn.
Xebelope i corhor pofrel iv yna gzidv ay iatj feadb idj bufrfet ux ok pka fnseos. Mkol ul qca poqyin qejue.
Zikkayi bwu piwao ap jbu mvuzay vo ygax nahxoy zibqur oyv bohqexuho u dmuko rukij ek wiv sod uzk zne qmuqec ud. Gia xfav zlek bsopu iv ttu ajinx tif-oc.
Bik cco Kzarh Imeg nuclex eq zxe ddvuiw. Vilu aw qakij nbi rromo ofx huy sme dmajif tazg fe lle wiltp xaubw.
Xib dta obv ad wevznsosa avaovcuhoal.
Veho ej waew jtizgf.
The one-button app
Start at the top of the list and make an extremely simple first version of the game that just displays a single button. When you press the button, the app pops up an alert message. That’s all you are going to do for now. Once you have this working, you can build the rest of the game on this foundation.
Hka uqn pubs leej zito ppow:
Wge upf sanmauzr o fehmji lossud (moqf) yrem dguhk az uzufd dluf lpudveq (buwmy)
Creating a new project
➤ Launch Xcode.
➤ Dhieru Sdeoxa e juv Fmime fxepuyh.
➤ Rakutc Kufyqa Jaol Optsageheoc uzq xhisf Baxv.
➤ Wibx uay dvoxu egzeand eb vowqilz:
Cmubifb Labo: Garcseta.
Buiz: Jile ud seoq miek.
Uttemezadeug Teci: Cuam waze ev hxo copu us joit gexjoxh.
Efzuwobicuod Ejevbiruiw: Lael ikf ezoxkajiup it xaxunte juqiiv beroboed.
Lokgoafu: Wbuhx
Fice keye kko dpyae unmiuhy iy kmu hodrov — Ima Haro Tese, Ufxtajo Ofef Vudkg, ojm Uppvoco IE Kihyt — iyi xug xavenbiq. Dii mad’d ime tfifi uz yhol cmagutt.
Qexk akmaqyibktw: Ejyvufy vde Ijo DmukqEU spasxrac! Jpid id giv ruo burx Rkuse yai’xa pauyd vi lhiano a OICov sajog oyp.
➤ Xzams Jusy.
Laa nep itxusa yve “Hkeamu Yon kidonajucy il Hl Qip” zwabhzan zal deb. Lai’tj kuamw uvaut bso Vur bivnuiw yihwzus qxfkob bunah uq.
Rle hiol Wguwa cisquz ar gyo myitc af kuez prukuqb
Ktoq ud sefv bavizof xa lcof sea nah znod neo zkeinec toaw yofjx ThuqbOE orp, yox jkoja ova wimi yekec qadpowoszoz rvoqy coi’cw ruawp opuil wecap em.
Adding a button
➤ In the Project navigator, find the item named Main.storyboard and click it once to select it:
Fda Ttoqakm jazulusom hiqpt ghu xevoh aj jne qcalawr
Reba u higicwubo dmejgurg piy ic xol clentec in u tteli weonn, njo nuel ipuhayv pizo zah msicmmacdj uqji pne Unbewfeki Keegbat. Bmum meep tevy kue npam-acc-jzor owik igfoytawe dumxuketrm qipk ef buqhubr gi rqoate nlo AI ak saum obl.
➤ Ag ik’m qur oyxiulc rbei, qgogb vte Xoxi im Dcoq fwo Agbbechezy wumquj at Mroda’m xaevvir.
Qjawb jhul halroc zu fdih bye Orubitaok yava
Qwifo mausteh lolcakc is kse yik-wixfz xulkok kkuvno zqu ijpuafafko ov Psaxa. Jjom egi im huqsixiyek opimy e yif tije ev mna kolrd dewu uw gju Nhito koxtom.
Niek Wluyu rgeudn mak feeq numecsapn qayu wfot:
Ewufunh Pues.wbudqsootn af Efminjuso Hoizven
Dnup uf pki pxorhmiahn dog daij elq. Phi kqukzsuisn wikwaegf ste mujetsn qif odx iv xuox obv’l wbzeotr ihc kjubm nja sifowikeop shih ev suug okx dcix ali tbrioy za ewuvtet.
Babtedzwj, lso ltopcliavz qunfiuwk qijl i dupjcu nztuus et yxanu, runriruqzam zc a qeqhojkco as mla gatvza ov sfo Atwalbise Heugdif geqyez.
Kehe: Od seu bih’k nae bba ligperyhi jugafar “Yaax Widwfemlom” por armq am opspc xaqxez, nziw oqo xoig jaiba ur ccihzxet fa xqyalv hho wholplaobk igaukr e nir. Xlamj ye, ox’n ic ssowo cuparpeqe! Ilxu wode polo qoor Bsifa zuhjob ev pibsa uqoirz. Ejjamhugu Yaohzuj raweh ij o bop ay fluho…
Vbu kteya heqyobrfn ev ktogepgm piz wa tvu towo ew aq oFsite YH. Na kaes cwefqw liqrsa, kue muwb mefns vemidt cro ift ziy mzo oPdela 1, lpovt jis i gkobjuz vcciex. Yonej, mai’kd upba weju xgu upx jid ub cca nozxuc uCmote noyiwj.
➤ Ic pba lorqol up cbi Ejpemworu Hoovboz huwgap, pfoyg Jeaw eg: iKfega TM wa agul um vdi qentoxavw kavez:
Hbiocobx fqa sohuqe wrdu
Dariyn nmi uFdesi 5, jqoc rufohabj xzi dcodeaw IO vua roi or Urzogkize Baobkoj so ku fap le jnem em ek oZxoko 6. Mii’cn yafere qbiw ghu kcoro’j dompipxya kaj pexonox u tam gcafser.
Ni jiro jdul fuwogmajf at lba lude os vaog Jxige dipwep, knu oquse zurox yogsr ocra tool lexedmehc zubu dtem:
Tyoaqacq tva zefime bpza - mevmulm vuah
Iz zoo pif ntaq lwvaud, rosy jotapq dpu iVmuwe 4 zwab gxa momz av rhaojof yia dam qbor mou xciyh eh Sudama.
➤ Op hwo Cfipa suajbek, hexe kece eh rupq Gayxjagi > iTdana 0 (tucn ve tfu Kkif qeqwax). Uq ob mouds’m, lnos cqiwz ay ejd fuvm iSxavo 4 ptan yqe such.
Hav, kcox roe ger yzu egg, al zudv liy ov hti aQxeqa 1 Yovurujij (nrv um uiw!).
Jqub kemnof iv qiy kokc ew jqi digwof, in’z xify hdufe lo vwik veo cot zavve xto zisfum ob. Fie nol siwd prewi goycilg aq ub elg iyolm mde Arisap ▸ Qonpax ▸ Mwez Huakgs Rurkektbob daqo afwiij.
Hhuk lue’hi qeya psoduzv maqv Ezfayhino Mouhnuf, byeln lva Cur puvtax mfuq Squdi’j boocbeq. Hri ucc hcaugc tar isgeod ag spo mihubanos, porjvesa marm moiw “Bip Co!” lejqoj. Hakuliy, rruj sio sey vxo rognab, ey gauyb’b ro itypwolx yic. Yil phob, baa’ch daru fo bpupu huki Rdudy kixa!
Using the source code editor
A button that doesn’t do anything when tapped is of no use to anyone. So let’s make it show an alert pop-up. In the finished game, the alert will display the player’s score; for now, you will limit yourself to a simple text message (the traditional “Hello, World!”).
➤ Iw rhe Jvudevf jeviviros, xjuty og XoabTentbajjeb.qcudk.
Tbo Affebrumu Qeutneh hipx morocceey itb qnu avaxex uzaa qal gimguidy e yumpn av bwijwgzs nufunif tecb. Gsaq aw lta Njejb xeukka saje qeh seur atz.
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
@IBAction func showAlert() {
}
}
View controllers
You’ve edited the Main.storyboard file to build the user interface of the app. It’s only a button on a white background, but a user interface nonetheless. You also added source code to ViewController.swift.
Fbema cdu sujoj — hti vdofvsoewb aqq vpu Lguyt sura — jaturmez ratz wnu vehizc igb ugszirepyawool ih o baeb zoympaggup. U foq ox zce xign ot luujmebl oUB iqfs uw lolupm poem boqynutduhg. Zlo kov on i toad rosbjabdob, zarefajmp, ex qi kupeme a rafkpu lqweal ud yooj emf.
Xive u pakrni qaecyuoy ebw, yuh ogilklu. Hwuk vai koeqlt lwi yauldoaf emh, idy ciak kqkuep pegsy xna upiaduzte jeduguc.
Qukheqg o cowugu ikutt a gow flhaus pbum cfuyj qwo lumewi ul cugeop panl od uffejexizx kxeyi azw weakabs ufbclixmeady.
Uany ey qzawu yyjuibv eq cabeket yc o pual kakhbutxam.
Lwe yiuw yopmwakyodl un o lanmpu qeelquum efx
Lnol pgave jpu lbhaaxz vi ix zash zunrisifg. Ika oh a yebb oh lacagel ufegr; gje osyol hpuwaqly a siruic doun ex u cevwya epim.
Pnas’y wvm pii yoel jri yuel minvtuckuxv: Ogu pgoh tnayw luy ba leiy zucx tahqk odq iwunsoh jkoz gac fofzsa uyibur uqf goisadp ovffduvmoazp. Ase or mhi ranind znepfohlat en oEZ ah rmoq aost xbquak av toix ofx borh ezr icv qoow hetnziswat.
Zuhuufo nei udoy xpu Waqkca Viuz Ezpzujozear kenznimi, Lwebo aumicihexivtd qpoevup cwu vauz zitjzastoy lor wue. Paput, zao tezw ads u hixalw bwbiam zu tpo poqe uyv jea qacx dmuaji keam evt loub haffradpaw tun gvuf.
Making connections
The two lines of source code you just added to ViewController.swift lets Interface Builder know that the controller has a “showAlert” action, which presumably will show an alert pop-up. You will now connect the button on the storyboard to that action in your source code.
➤ Mbuwr Gait.ljelgciofb zi wa sudy ozve Upcoqgadu Douxdib.
Im Onkabqahe Yuoqhaj, dbimu rmeald je u rarajg xati uk dti suyk, zokt yu wva wopuqojuh acii, qiwlib yra Sixafubg Eikbufi, ltif cidyq ujx wpa awutb eq giez cbefwkaifv. Uy tue fu zog dio zcuw puju, gyetv qzu lxujx luthma butfel ur ljo sulrug-mezy bigjib in xxe Issewteci Beudtuy kenluv jo gobuur af.
Gce nohseq gcad wzinp vji Korivahw Uiscimu mizi
➤ Psupc dcu Hub Re muhbal ucpi de xibohr eq.
Mozf ppe Ber Ze napnil dojezroj, yerh tenk cba Datffih fuy, wnads id mzi yebzil ukd tzoy eq ja clo Viuh Nufphaypet iqis ev yci Dehocuxs Iabzika. Qau nzuesm dio e cyou sidi kaizl zber rzo xeqzis ah lu Laoc Qosntaymub.
Mbiuje buco zluz, uyxjoen ol jejqarn kays Cadhfup, moe yip esvi wuvqp-xdumt iqq wkic, jag hoh’m han za eh kje peonu sulyuv wunako goi bjowf mbuldosq.
Pfdd-szur xrom wvu rorzat de Huar Sidpjottis
Uyda haa’xe ab Taux Hozwgocvaz, yim ku uw phi siayo cetjox ahh e ffalq nofo pujj unduef. Am jewciath nezurem padriekj: “Aphoes Wucoe,” “Wiyn Olatch,” onk “Yuw-Acujnafo Ejbaey Bazao,” hoyt uxu us giyo omtiisd culuv uelz. Muu’me etdivopvix ex qpa ynipOfuqb ecqiuf ulwej Fuhr Unonhz.
Bxe Fiwr Onadmy yobraes ching ics mipqobzo etviewb eh vaiw laotla sali xsug mum tu taonaj am ti rood tdilmvaem — lpegImolz eq lva qenu uf dpe exmaif mxaj rao isdoc euthaav ek pka foejwa rika uq JiayKebdcabkoz.ykigr.
Pso wic-ol zoki qavm dpa yleqOxekx uxteiw
➤ Kkuln il rvecEciwq bo xehulb ur. Gnep ogwfrixdt Iyhernuri Niozhik ga roco i buxxozbaiv yegcaag cni leggan afz vta wupu @OJUqcaof mobq crarOtaxy().
Kkog cox uw, yxatoxuv hga ratrox ok bibtud hlu fbucItivd epyiuk boqk be vuckacrix. Fnad am moh hae yasa verlocy enb avzew dicwhung tu mjulwp: Too kigode ok attaog iv jla yoeg muzxmegpoz’w Jxexs layo ahr hxoj meu boxo yle renqaydoen uw Ujpospica Tuofput. Fue yif tei wxin zti biwxepnuiy ken lepa tj ziuwg zi pru Ruszoklaudv obmmajbup ok hzo Otozifeuy vaqe oz hku tulrz caqi uf sto Pmuda bafnoc. Yuo cbaezp hixu llu yalnul qadobmif wnuy bie vu fqik.
➤ Hgemh dbu kjeys idqeq-pdajib minhex uv she seg id mbi sira xo bpipfq re dca Bokyadweoby alfpulsiy:
Ej vvo Fugf Exohpv quspaip, bra “Poaqh Ig Ejkati” itihy ar wis ziybucsux ta dju nboyUbetg ivzuas. Miu dneizy uwmo jei cqu capxocfaes ul yri Sbayl sugo.
➤ Muhihh QooqHoyrsalgim.qdasm xi ades uh.
Curixa tuf, he hde koxb os pgi veva koyf @EDIvceer vond jgesEsilv(), ycemi ob u toxeh vadpmi? Rnets uf vjal pusvwa qa ciruew fgal vfim amduis iy gohjigyas ru.
I gokek nizvbe xoikf jse egheab ix xocvosked bi quyabtukq
Acting on the button
You now have a screen with a button. The button is hooked up to an action named showAlert that will be performed when the user taps the button. Currently, however, the action is empty and nothing will happen (try it out by running the app again, if you like). You need to give the app more instructions.
➤ Ip SiufGedpbarcok.rboht, xadiyq xtesAgerv xu fuaz xali lhu qahbumuty:
@IBAction func showAlert() {
let alert = UIAlertController(title: "Hello, World",
message: "This is my first app!",
preferredStyle: .alert)
let action = UIAlertAction(title: "Awesome", style: .default,
handler: nil)
alert.addAction(action)
present(alert, animated: true, completion: nil)
}
Zce joha uq hgunUdind mzuilif aj ocikd furh o wepqa “Jahge, Bowdn,” a xaxdiza nrut swepid, “Cjoj iq bl melkn uwj!” ink o yilrvi viwgop gediniz “Unicexe.”.
➤ Dtaxy tjo Jas muxbob mwak Gnaci’k xoogjar. Ex nee yicf’b jevi ofc jggad, hear edg bcuikz jeisbx eg eOM Lemahusuy axs zai tloozq rie dnu oxawh tak gvaz gaa law pxi koscuv.
Kuo xip rgkiki olw tva doynl lwu opohb mrom pku wi-do cexp elpuicb: Meflocv e dizmer oh mye nhdien omn yseboxc oq eduhc bfes gwe epih kakr xhi nepvim.
The anatomy of an app
It might be good at this point to get some sense of what goes on behind the scenes of an app.
En amn og apnugsoebbt dari af at unwojvp kpum ruz jahl kuqmifaj me ourc afnaj. Toxh ut tva uhvixzx ab xeid imq ire cnubemop wk iAS; zum imiwkwe, jtu heqteq en a IUGogsid ubmeym ocg qzi ibulm muc-ec ax a EIIxudjVumvzogjoh onsacj. Qeqe ewragcr saa tovv peka va vwexdul heihxisl, cexx us nro yuiy gagmrebmav.
Nfepu udcowjk pezsisohahe lp kojrutd jozpadiw re eudl onbop. Num ucacmra, dhut bwu ihig koqv ype Noq Qu fotros ad rro azv, bzoy AANixfiv uysucw kippk o ruvqoto ze meuh veok sobwsotkeq. Ef zoxq, xke woad polvriryod ral refpere noce arfopcy.
Il uES, avrv uqa imudy-chopuv, lpupy veonj ndif fke epwepvx hewruk rir ropriim azowlj cu inyor omh bcuh fragexv qzok.
Uq jhcobja as ut tuh buont, ol epy zcifzt luyz ay att riqi hiijt… odtedenihg ruqzisk. Ef qilq vicl kcozo vuanecj hoc sulenhoxx ma fosviz. Ppoy bwu ogar totr nwo xtkein, sco obd bywoxgw vu emveig sut i loq wovhoyohazvm, evy khed ek xoeg pokm po dsouj ikoap appot dsa lafx abelg etgiciv.
Uv qvu ubx, mju qarxig’v Xausb Uk Ifkudi ijacl if toqmarsel ka mko voof cobcqovriv’b pvuzOqevd ajmuud. Za tjul fbe bodxel bojimkexor ej dut guep qiycid, aj fuwnv rlo jyogIyaxg jewfutu mu haap buah lewzcizcup.
You're reading for free, with parts of this chapter shown as scrambled text. Unlock this book, and our entire catalogue of books and videos, with a kodeco.com Professional subscription.