BeginningiOS
Storyboardingwith
Xcode
EasilyDesignandDevelopYourApp,fromConcept
andVisiontoCode
Copyright©2012byRoryLewis,YuliaMcCarthy,andStephenM.Moraco
Allrightsreserved.Nopartofthisworkmaybereproducedortransmittedinanyformorbyanymeans, electronicormechanical,includingphotocopying,recording,orbyanyinformationstorageorretrieval system,withoutthepriorwrittenpermissionofthecopyrightownerandthepublisher.
ISBN-13(pbk):978-1-4302-4272-7
ISBN-13(electronic):978-1-4302-4273-4
Trademarkednames,logos,andimagesmayappearinthisbook.Ratherthanuseatrademarksymbol witheveryoccurrenceofatrademarkedname,logo,orimageweusethenames,logos,andimagesonlyin aneditorialfashionandtothebenefitofthetrademarkowner,withnointentionofinfringementofthe trademark.
Theuseinthispublicationoftradenames,trademarks,servicemarks,andsimilarterms,eveniftheyare notidentifiedassuch,isnottobetakenasanexpressionofopinionastowhetherornottheyaresubject toproprietaryrights.
PresidentandPublisher:PaulManning LeadEditor:MatthewMoodie
TechnicalReviewer:MatthewKnott
EditorialBoard:SteveAnglin,MarkBeckner,EwanBuckingham,GaryCornell,MorganErtel, JonathanGennick,JonathanHassell,RobertHutchinson,MichelleLowman,MatthewMoodie, JeffOlson,JeffreyPepper,DouglasPundick,BenRenow-Clarke,DominicShakeshaft,Gwenan Spearing,MattWade,TomWelsh
CoordinatingEditor:BrigidDuffy CopyEditor:CorbinCollins
Compositor:BythewayPublishingServices Indexer:SPiGlobal
Artist:SPiGlobal
CoverDesigner:AnnaIshchenko
DistributedtothebooktradeworldwidebySpringerScience+BusinessMedia,LLC.,233SpringStreet,6th Floor,NewYork,NY10013.Phone1-800-SPRINGER,fax(201)348-4505,e-mailorders-ny@springer-sbm.com,orvisitwww.springeronline.com.
Forinformationontranslations,pleasee-mailrights@apress.com,orvisitwww.apress.com.
ApressandfriendsofEDbooksmaybepurchasedinbulkforacademic,corporate,orpromotionaluse. eBookversionsandlicensesarealsoavailableformosttitles.Formoreinformation,referenceourSpecial BulkSales–eBookLicensingwebpageatwww.apress.com/info/bulksales.
Theinformationinthisbookisdistributedonan“asis”basis,withoutwarranty.Althoughevery
Tomyamazingmom—themostcaringandsupportivepersonI’veeverknown. Thankyouforyourendlesslove!
—Yulia
ToDonna,mywifeof31years,mybestfriendandtravellingcompanionthroughthislifeand aroundthisbeautifulplanet.Withoutyoursupportandencouragement,manyofmyefforts
throughoutourtimetogetherwouldnothavebeenpossible,nornearlyasenjoyable.Ilook forwardtoourupcomingyearstogether.
TomysonSteve,forsharinginourmanyendeavorstogether,foryourgraphicscontributionto ourfirstjointiOSapp,9CardGolfintheAppStore,butmostimportantlyforbeingashining exampletome,andIhopetoothers,ofconstantself-motivationandconstantlearning,andfor maintainingayouthfulpassionforlearningabouttheuniverseinwhichwelive.Ilookforward
ContentsataGlance
■
Foreword:AbouttheAuthors... viii
■
AbouttheContributingAuthor ... xii
■
AbouttheTechnicalReviewer... xiii
■
Introduction... xiv
■
Chapter1:Preliminaries ... 1
■
Chapter2:Fundamentals ... 27
■
Chapter3:StoryboardingwithMapView ... 91
■
Chapter4:BuildingaUtilityApplication... 159
■
Chapter5:StoryboardingaPage-BasedApp... 211
■
Chapter6:MasteringTableViewswithStoryboarding:CoreData… ... 273
■
Chapter7:MasteringTableViewswithStoryboarding:Designing…... 305
■
Chapter8:MasteringTableViewswithStoryboarding:Coding…... 383
■
Chapter9:SingleView##:wanderBoardPartI…... 477
■
Chapter10:SingleView#3:wanderBoardPartII... 503
■
Chapter11:SingleView#3:wanderBoardPartIII ... 569
Contents
■
Foreword:AbouttheAuthors... viii
■
AbouttheContributingAuthor ... xii
■
AbouttheTechnicalReviewer... xiii
■
Introduction... xiv
■
Chapter1:Preliminaries ... 1
NecessitiesandAccessories ...1
GettingaMac ...2
GettingOSX...4
BecomeaDeveloper...6
GettingReadyforYourFirstiPhone/iPadProject...17
InstallingDemoMonkey...21
■
Chapter2:Fundamentals ... 27
helloAlien:AQuickExampleApplication...35
Preliminaries ...36
Step1:CreateaButtonThatSeguestoaSecondaryView...38
Step2:PassInformationBackfromaSecondaryView(AlienView)totheMainView...47
Step3:SendInformationOuttotheSecondaryView(AlienView)...70
Step4:CustomSegue ...83
Step1:Setup...162
Step2:PreppingtheStoryboard...171
Step3:CodingtheFlipsideViewController...181
■
Chapter5:StoryboardingaPage-BasedApp... 211
futureTravel:APage-BasedApp ...212
Preliminaries...212
Step1:CreatefromTemplate...213
Step2:PrepStoryboard...225
Step3:Code:ModelController ...236
Step4:Code:DataViewController ...254
Step5:Code:RootViewController ...265
■
Chapter6:MasteringTableViewswithStoryboarding:CoreData… ... 273
bookManager:AMaster-DetailApp...274
Preliminaries...277
Step1of3:SetUpfiles,Images,CoreDataandDataModel ...278
■
Chapter7:MasteringTableViewswithStoryboarding:Designing…... 305
Step2:StoryboardingtheApp ...305
ConfiguringtheMasterScene ...306
DesigningtheTopLevelViews:CategoriesScene...311
DesigningtheTopLevelViews:AuthorsScene...321
LayingOuttheMainBookListView:BooksScene ...329
StoryboardingtheDetailView:BookDetailScene ...341
CreatingtheUIforEnteringandSavingNewData:AddBookScene...348
MakingFinalTweaks...374
■
Chapter8:MasteringTableViewswithStoryboarding:Coding…... 383
Step3:InserttheCodeBehindtheStoryboardElementsandTweak… ...383
CreatingaCustomUITableViewCellsubclass ...384
ModifyingtheDetailViewController ...387
CreatingtheSelectionViewController...397
■
Chapter10:SingleView#3:wanderBoardPartII... 503
Step3:FinishtheViewControllerHeaderandImplementationFiles...504
Step4a:CreatetheNextEightSceneswithAssistance ...510
Scene2...512
Scene3...528
Scene4...538
Scene5...546
Scene6...551
Scene7...554
Scene8...559
Scene9...562
■
Chapter11:SingleView#3:wanderBoardPartIII ... 569
Step4b:CreatetheFinalNineScenes...569
■
Chapter12:HowFarYou’veCome... 609
FinalThoughts ...609
MultipleStoryboardFilesinOneApplication...610
HavingAll.xibFilesinOneStoryboardBasket...611
WhatDoYouMean,NotAllScenesAreAppropriatelyPlacedinStoryboardFiles?...612
Hey,IHaveQuestions! ...612
Foreword:AbouttheAuthors
ThethreeauthorshavefoundabeautifulwaytoleadthebeginnerintoStoryboardingandatthe sametimeshowtheoldschoolcodersofObjective-Canewexquisitemethodologyforlearning anddebuggingthisincredibletool.Essentially,youhaveaguruofexplainingcomplexObjective-Ctobeginners,aformerAppleiOSintern,andasuper-successful,old-schoolcodershowing manypeoplefrommanydifferentwalksoflifethealphaandomegaofStoryboardcreation, debugging,andtweaking.
Dr.RoryLewis
StephenM.
Moraco
landedachoice,on-campusjobasaproctorinthecomputerlabsintheL.C.SmithCollegeof Engineering.EventhoughhewasstrugglingwithsubjectsintheElectricalEngineeringprogram, hewasalwaysthereattheHelpDesk.ItwasadauntingexperienceforRorybecausehisjobwas onlytohelphisfellowstudentswithcomputerlabequipmentquestions,yetheinvariablyfound hisclassmatesaskingdeeperandharderquestions:“Dude,didyouunderstandthecalculus assignment?Canyouhelpme?!”
Thesestudentsassumedthat,becauseRorywastheproctor,heknewtheanswers.Afraid andfullofself-doubt,hesoughtawaytohelpthemwithoutrevealinghisinadequacies.Rory learnedtostartwith:“Let’sgobacktothebasics.Rememberthatlastweekwhentheprofessor presenteduswithanequation…?”Bygoingbacktothefundamentals,restatingandrebranding them,Rorybegantodevelopatechniquethatwould,moreoftenthannot,leadtoworking solutions.Bythetimehissenioryearrolledaround,therewasoftenalineofstudentswaitingat theHelpDeskonthenightsRoryworked.
Fast-Forward17Years
Picturealong-haired,wackyprofessorwalkingthroughthecampusoftheUniversityofColorado atColoradoSprings,dressedinastunningcontrastofold-schoolanddropout.Ashewalksinto theEngineeringBuilding,he’sgreetedbystudentsandfacultywhosmileandsayheartyhellos, allthewhileprobablyshakingtheirheadsathistweedjacket,GratefulDeadt-shirt,khakipants, andflip-flops.AshewalksdownthehalloftheComputerScienceDepartment,there’salineof studentsstandingoutsidehisoffice.Reminiscentofthelineofstudentsthatwaitedforhimatthe HelpDeskinthoseearlyyearsasaproctorinthecomputerlab,theyturnandgreethim,“Good morning,Dr.Lewis!”ManyoftheseUCCSstudentsaren’teveninhisclass,buttheyknowDr. Lewiswillseethemandhelpthemanyway.
Past—Present—Future
Dr.Lewisholdsthreeacademicdegrees.HeearnedaBachelorofScienceinComputer
EngineeringfromSyracuseUniversity.Syracuse’sL.C.SmithCollegeofEngineeringisoneofthe country’stopschools.It’stherethatIntel,AMD,andMicrosoftsendtheirtopemployeestostudy fortheirPhDs.
UponcompletinghisBS(withemphasisonthemathematicsofelectroniccircuitryin microprocessors),hewentacrossthequadtotheSyracuseUniversitySchoolofLaw.Duringhis firstsummeratlawschool,Fulbright&Jaworski,thenation’smostprolificlawfirm,recruited RorytoworkinitsAustinoffice,wheresomeoftheattorneysspecializeinhigh-techintellectual-propertypatentlitigation.Aspartofhisclerkingexperience,LewisworkedontheinfamousAMD v.Intelcase;hehelpedassessthealgorithmsofthemathematicsofmicroprocessorelectrical circuitryfortheseniorpartners.
mathematicalanalysisofthegenesisofepilepsywithrespecttothehypothalamus.However, withtheadventofApple’srevolutionaryiPhoneanditsuniquelyflexibleplatform—andmarket— formini-applications,games,andpersonalcomputingtools,hegrewexcitedandbegan
experimentingandprogrammingforhisownpleasure.Oncehisownfluencywasestablished, LewisfiguredhecouldteachaclassoniPhoneappsthatwouldincludenon-engineers.Withhis insiderknowledgeasaniPhonebetatester,hebegantointegratetheparametersoftheproposed iPadplatformintohislessonplans—evenbeforetheofficialreleaseinApril2010.
Theclasswasaresoundingsuccess,andthefeedbackwasoverwhelminglypositive, fromstudentsandcolleaguesalike.Whenapproachedabouttheprospectofconvertinghis courseintoabooktobepublishedbyApress,Dr.Lewisjumpedattheopportunity.Hehappily acceptedanoffertoconverthiscourseoutlines,classnotes,andvideosintothebookyouare nowholdinginyourhands.
WhyWriteThisBook?
ThereasonsDr.Lewiswrotethisbookarethesamereasonsheoriginallydecidedtocreateaclass forbothengineeringandnon-engineeringmajors:thechallengeandthefun!AccordingtoLewis, theiPhoneandiPadare“…someofthecoolest,mostpowerful,andmosttechnologically advancedtoolsevermade—period!”
Heisfascinatedbythefactthat,justunderneaththeappealingtouchscreenofhigh-resolutionimagesandfunlittleicons,theiPhoneandiPadareprogrammedinObjective-C,an incrediblydifficultandadvancedlanguage.Moreandmore,Lewiswasapproachedbystudents andcolleagueswhowantedtoprogramappsfortheiPhoneandwouldaskhisopinionontheir ideas.ItseemedthatwitheverynewupdateoftheiPhone,nottomentiontheadventofthe expandedinterfaceoftheiPad,thefloodgatesofinterestinprogrammingappswerethrownopen widerandwider.Wonderfulandinnovativeideasjustneededtheproperchanneltoflowintothe appropriateformatandthenouttotheworld.
Generallyspeaking,however,thepeoplewhowritebooksaboutObjective-Cwritefor peoplewhoknowJava,C#,orC++atanadvancedlevel.So,becausethereseemedtobenohelp fortheaveragepersonwhohasnosuchknowledgebutwhohasagreatideaforaniPhone/iPad app,Dr.Lewisdecidedtolaunchsuchaclass.Herealizeditwouldbewisetousehisownnotes forthefirsthalfofthecourseandthenexplorethebestexistingresourceshecouldfind.
Asheforgedaheadwiththisplan,LewiswasmostimpressedwithBeginningiPhone3 Development:ExploringtheiPhoneSDK.Thisbest-sellinginstructionalbookfromApresswas writtenbyDaveMarkandJeffLamarche.Lewisconcludedthattheirbookwouldprovidean excellent,high-leveltargetforhislessons,a“stepping-stones”approachtocomprehensiveand fluentprogrammingforallofApple’smultitouchdevices.
writinginhigh-levellanguagessuchasPL/I,RPG,ANSIC,C++,C#,Objective-C,andassembly languagesformoremicroprocessorsthanhecancountontwohands.PriortojoiningHewlett-Packard/AgilentTechnologies1989,hewasanembedded-systemsdesigner/developer.Stephen isapastmemberoftheLarge-scaleLogicAnalyzerTeam,buildingsystemrecoverymediaand writingtriggering/capturedriversformultichannelcustomdatacaptureASICs.Asasoftware processengineer,heworkedwithmedium-sizedR&Dteamsdevelopingtechniquestoimprove therateofreleaseandinitialreleasequalityofsoftwareproducts.Stephenalsodesignedand wroteanoperatingsystemforopticaldrivesproducedbyHewlett-Packard.
Stephen’sprofessionisalsohishobby.Heisastrongbelieverinconstantlearningandof constantlypracticingwhathe’slearning.AllduringhiscareerStephendevelopedonnon-work-relatedprojectsasaformofself-training.Heenjoysdesigningandbuildinghisown
hardware/softwaresystemsforhomecontrolandgeneralexperimentation.Stephenalso developedfirmwareforkeyintegrationsystemsthatflyaboardamateurradiosatellitesand developedhardwareandsoftwarefortestingthesesystems.
StephenandhissonStevebothenjoybuildinglargeLEGOmodelsandworkingwith LEGOMindstormsrobotics.SonSteveisstudyingphotography,andtogetherthey’vevolunteered withColoradoFirstLEGOLeagueforthepastfiveyears,withDadrefereeingtheMindstorms Roboticstournamentsfor9–14year-oldsthroughoutColoradowhilesonStevedocumentsthe excitementoftheeventsthoughhisphotography.
Inthefallof2009,fatherStephenandsonStevetookanObjective-C,iOSprogramming classtogetherattheUniversityofColoradoatColoradoSprings.ShortlythereafterStephen startedhiscompanyIronSheepProductionsLLC,thenameunderwhichhesellsthehardware andsoftwarehe’sdeveloped.Afterasuccessful22-yearcareerwithHewlett-Packard/Agilent Technologies,Stephenisnowaretiredprofessionalsoftwareengineerand…asuccessfuliPhone andiPadappprogrammerwhosellshisappsontheiTunesstore.
YuliaMcCarthy
YuliaisaSenioriOSDeveloperatInspireSmartSolutions,Inc.,alocalDenverfirmspecializingin innovativemobilebusinesssolutions.Aftergraduatingfromoneofthebestclassicuniversitiesin RussiawithaBSinMathematics,shewentontoconquerthesnowypeaksofColorado,pursuing herdreamofsnowboardingandadventure.Soonshedecidedtopursueagraduatecareerin ComputerScienceatUniversityofColoradoatDenverwhere,aftertakinganiPhone
developmentclasswithDr.Lewis,shequicklyconvertedintoaMacuserandtransferredallher passionandincredibleabilitytoprogramandsolvecomplexproblemsintodevelopingiPhone andiPadapps,whichhasbeenhernewpassioneversince.HeramazingtalentsoonattractediOS recruitersatApple,andnowYuliaisevenmoreinspiredanddevotedtoCocoaTouch
AbouttheContributingAuthor
BenEastonisagraduateofWashington&LeeUniversityandhasaBAin Philosophy.Hiseclecticbackgroundincludesmusic,banking,sailing,hang gliding,andretail.Mostofhisworkhasinvolvededucationinoneformor another.Bentaughtschoolfor17years,mostlymiddle-schoolmathematics. Morerecently,hisexperienceasasoftwaretrainerandimplementer
reawakenedhislong-timeaffinityfortechnicalsubjects.Asafreelancewriter, hehaswrittenseveralsciencefictionstoriesandscreenplays,aswellasfeature articlesformagazinesandnewsletters.BenresidesinAustin,Texas,andis currentlyworkingonhisfirstnovel.
AbouttheTechnicalReviewer
Introduction
IneditionsofRory’spreviousbookiPhoneandiPadAppsforAbsoluteBeginners(Apress),there wereonlytwowaystoteachthereaderhowtomakeaniOSappuserinterface.Thefirstwasto writeeverythingincode,andtheotherwastouseInterfaceBuildertocomposeaWindows-based app.ButthingshavechangedwithStoryboarding…boy,havethey!
StoryboardingfirstappearedwithXcodeversion4.2.Whenwefirstsawthescenesthat madeupanapp,wethoughtStoryboardwasfantastic.ItwaswonderfulhowStoryboardallowed ustonavigateapaththroughoutappinavisualway.AlmostimmediatelyRoryfoundfreshmen studentscomingintohisoffice,knee-deepintroubleusingStoryboards.MeanwhileXcode expertswerepooh-poohingStoryboards.Thisbookhelpsthenoviceunderstandthepowerof StoryboardsandcanhelpevenexpertsinXcodetounleashit.
Inthisbookyou’lldiscoverhowXcode’sInterfaceBuilder’ssupportforStoryboardingin iOS5makesdesigningyouriOSappssomucheasier.Storyboardingletsyougraphicallyarrange allyourviewswithinasingledesigncanvas,whereyoucanthendefinetheapp’slogicalflowand evenassigntransitionanimations.You’llbeabletolearnhowtouseStoryboardstoquicklygo fromconcepttoafullyfunctionaliOSapplication.
First,wegooverthefundamentalconceptsofStoryboardingandthetechnologybehind it.Wethenwalkyouthroughbuildingsevencompleteprojectsthatadvanceyouthroughusing variousStoryboardingfeatures,coveringthemostimportantaspectsyouneedtoknowto successfullycreateyourownappsfromstarttofinish.Bytheendofthisbook,you’lleventually seehowtouseStoryboardingwithalmosteveryapplicationtemplateofferedbyXcodeandyou’ll learnwhichStoryboardingtechniquesaremostsuitableincertainscenarios.
WorkingwithStoryboardinginvolvesmuchmorethansimplydragginganddropping ViewControllersontoacanvas.Inthisbookweshowhowtostartfromscratchandbuild completeappsusingStoryboarding.AlongthewaywedemonstrateusingcommoniOS technologiesasMapViews,PageViewControllers,SplitViewControllers,CoreData,Table Views,andmore—andwetellyouhowtheyallfittogetherwiththenewStoryboardingfeature.
WhatYou’llLearn
fromwithinthecode.Additionally,you’lllearnhowtoeasilyparseJSONdatafromaremote server(suchasFlickr)usingnothingbutthenewiOS5API.
InChapter4,you’llfindouthowtodevelopafunutilityappusingStoryboardingtargetedforthe iPad.You’lllearnthefoundationofmanyapps,whichishowtoplacecontrolsonthesettings screenofautilityapplicationandtoreturnthosesettingstotheMainViewoftheappviathe SettingsViewdelegateprotocol.You’llgetagoodgraspofthemainStoryboardingspecificsofthe iPadenvironment,includingSplitViewControllers,PopoverView,andiPad-specificsegues.Asa partofbuildingthischapter’sproject,you’llalsodemonstratehowyoucanuseabuild-itmedia frameworktoenableyourapptoplayaudiofiles.
InChapter5,weexploreaveryspecialXcodetemplate:thePage-BasedApplicationtemplate. Unlikeothertemplates,itdoesn’tletyouoptoutofusingStoryboarding.Inthischapter,you’ll learnthepowerfultoolsthatletyoucreatePageViewControllertransitions.Wedigdeepintothe insandoutsofhowtousetheUIPageViewControllertobuildaniPadbrochurewithbeautiful, built-inpage-curlanimationsandcustomlayout.
Chapters6–8bringtoyouawholenewworldofStoryboardingfeaturesthatdramaticallychange thewaytoprogramTableViews.WewalkyouthroughamoreadvancedTableViews-based projectthatutilizesCoreDatainthebackend.You’lllearncriticalStoryboardingtechniquessuch asDynamicCellPrototypinganddesigningStaticTableViews.Mostimportantly,inthischapter weshowyouhowtodesignyourentireappworkflowentirelyintheStoryboardbeforedoingany codingatall.
InChapters9–11you’lllearntodevelopacoolgameappthatstretchesyourknowledgeofhow seguescanbeusedtoprovidemuchmorecomplexnavigationpathsbetweenscreens.
WhoShouldReadThisBook?
ThisbookisforreadersofRoryLewis’slastbook,iPhoneandiPadAppsforAbsoluteBeginners, butit’salsoforthebeginnerwho’sneverprogrammedbutwhocanusetheStoryboardingtoolin Xcodetogetupandrunningfast.ThisbookisalsoforexperiencediOSdeveloperswhowant tolearnStoryboardingtoquicklycutdownonappdevelopmentanddebuggingtime.
Forthebeginnerwhohasneverprogrammed,BeginningiOSStoryboardingwith Xcodeshowshowtoextractthosecoolandinnovativeappideasyouhaveinyourheadintoa workingappreadyforsaleontheAppStore.Evenifyou’reanintermediateorpro-level Objective-Cdeveloper,youcanstilllearntheinsandoutsofXcode’snewStoryboarding feature—andfindnewwaysofbuildinganddebuggingyournewStoryboardingapp.Yup:This bookisforyou,too.
1
Chapter
Preliminaries
Thisintroductorychapterwillmakesurethatyouhavealltherequiredtoolsand accessoriestoproceedfullyandconfidently.Threetypesofreadersarelikely readingthisbook.OnegroupcanskiptoChapter2immediatelywithoutreading Chapter1.AnothergroupmayonlyneedtoreadonesmallsectioninChapter1 andthenmoveontoChapter.ThethirdgroupshouldreadChapter1very carefullybeforemovingon.
Group1:YouownaMac.Youhaveexperiencecodingwith
XcodeonyourMac.Youhaveanup-to-dateiOSSDKandan up-to-dateversionofXcode.Youalsohaveexperiencewith DemoMonkey,andit'sinstalledonyourmachine.Ifallthisis true,meetmeinChapter2.
Group2:YouownaMac.Youhaveexperiencecodingwith
XcodeonyourMac.Youhaveanup-to-dateiOSSDKandan up-to-dateversionofXcode.However,youdon'thave experiencewithDemoMonkeyorit'snotinstalledonyour machine.Pleasecheckoutthesection"Installing
DemoMonkey"inthischapterandthenmeetmeinChapter2.
Group3:Youareaseekerofknowledgeandhavebegun
travellingdownawonderfulroad.Weneedtocheckyour backpackandmakesureyouhaveallthetoolsyou'llneedfor yourjourney.Solet'sstartrighthere.
Necessities and Accessories
minimalrequirementswhichyoumaynotcompletelyunderstandrightnowbut that’sOKjustrollwithmeforasecond,I’llexplaineverythingaswegothrough thesesteps.
NOTE:WheneverwesayiPhoneoriPad,we’rereferringtoanyiPhoneoriPadOS device,includingtheiPodtouch.AlsowhenwesayMacintoshHD,yoursmaybe namedsomethingdifferent.
Briefly,youwillneedsixthings:
AnIntel-basedMacintosh
ThecorrectoperatingsystemforyourMac(OSX10.7.4Lion
orlater)
Bearegistereddeveloperorbesimulator-based(discussedin
detaillaterinthischapter)
TohavethecorrectoperatingsystemforyouriPhone(iOS5
orabove)
TohavethecorrectSoftwareDevelopmentKit(SDK)foryour
iPhonethatrunsaprogramcalledXcode(version4.3 andabove)
ToinstallandrunDemoMonkey
Let'sgointoeachoftheseinabitmoredetail.
Getting a Mac
IfyourMacwasmanufacturedafter2006,you’reokay.Oneoftheauthors purposefullyprogramseverythingonaMacBookboughtin2008.Allthevideos onthenetarescreencastfromDr.Lewis'sMacBookfrom2006;orifhe
broadcastsfromhis2010iMac,hefirstrunsitonhisMacBookboughtin2006.
Youdon’tneedthelatestrevved-upMac.Ifyouhaven’t
IfyoudoownanolderMac,youmaybeabletoaddsome RAM.MakeafreeappointmentattheGeniusBaratanApple StoreandaskwhethertheycanincreasetheRAMonyour oldermodelMac,andifso,askaboutthemaximumtheRAM canbeincreased.Thenaskexplicitly:"Canthisoldcomputer runLion,atleast10.7.1,andXcode4.3orlater?"Notethat someoftheappsinthisbookwillworkusingXcode4.3on SnowLeopard.Butifpossible,trytogetLion(atleastMacOS X10.7.4)andiOSSDK4.3.
Ifyoudon'thaveaMac,you'llneedtobuyoneifyouwantto
followalongwiththisbookandorprogramObjective-Cto makeiPhoneapps.Keepinmindthat,asmentioned,wehave madeapointtocodeandruneveryprograminthisbookon Apple’ssmallestandcheapestmodel,theMacBook.Apple hasdiscontinuedtheMacBook;itnowsellstheMacBookAir for$999,whichismoreadvancedthantheAuthor'sMacBook. YoucanpurchaseaMacBookoneBayandothersuchsites. SeeFigure1-1.
Getting OS X
YouwillneedthecorrectversionofOSX.Atthetimeofthiswriting,thatversion
isOSX10.7.4. Weneedtomakesurethatyouhavethelatestgreatest
operatingsysteminsideyourMac.Weseealotofemailsandforumquestions revealingthatmanyofyouwillthink:‘‘Ah,mycodeprobablydidnotcompile correctlybecauseDr.LewishasadifferentversionofOSXor/andiOSonhis machine…’’
NOTE:Evenifyouthinkeverythingisuptodate,wesuggestyoufollowalongwith theprocedureinthissectionandmakesureyoursystemhasthelatestOSXandthe latestiOSinsideit.Wesaythisbecauseasyoufollowalonginthisbookandtackle alltheprograms,therewillbetimeswhenyourcodedoesn’tworkthefirsttimeyou runit.
Tomakesureyoursystemisrecentenoughtofollowalongwiththebook, pleasedothefollowing:
1. CloseeveryprogramrunningonyourMacsothatonlythe
Finderisrunning.
2. Clickthelittleappleintheupperleft-handcornerofyourscreen
andselectAboutThisMac.You'llseethewindowshownin Figure1-2.MakesureitsaysOSX10.7.4.
NowtomakesureyouhavethelatestsoftwareonyourMac:
1. WithallyourprogramsclosedexceptfortheFinder,clickthe
appleintheupperleft-handcorneragainandselectSoftware Update…asillustratedinFigure1-3.
2. Ifupdatesareavailable,clickContinueandfollowthe
instructionsandfourscreenprompts,asshowninFigure1-3.
Ifbythetimeyouarereadingthisbook,yourealizethatyourversionofOSXor iOSmakesmypicturesseemeddated,don'tfreakout.Wehaveanonlineforum whereweandvolunteerslovetohelpothers.Wealwaysupdatetheforumwith newsaboutrecentupdatesofOSXandiOS.Youcanvisittheforumhere:
www.rorylewis.com/ipad_forum/ http://bit.ly/oLVwpY
Become a Developer
YouwillneedtobecomearegistereddeveloperviatheiPhone/iPadSoftware DevelopmentKit(SDK)for$99.Oryoucanpay$0foranintroductorysetof bellsandwhistles.
Making Your Choice
Ifyouareastudent,it’slikelythatyourprofessorhasalreadytakencareofthis, andyoumayalreadyberegisteredunderyourprofessor’sname.Ifyouarenota student,youneedtodecidewhichtypeofdeveloperyouwouldliketobe.Here areyouroptions:
$0option:YoucangototheAppStoreanddownloadXcode
forfree.Thisisfine,butbearinmindthatunlessyoubecome adeveloper($99),youwillonlybeabletoseetheappsyou codeandprograminthisbookrunningontheiPhoneoriPad Simulator.Thatmeansyoucan'trunthemonarealphysical iPadoriPhone.Youalsowon'tbeabletosellyourappson theiTunesstore.Lastly,youwon'tbeabletologintothe developersitetoviewcodesnippetsandupdates,beta-test newproducts,orbeapartoftheAppleonlinecommunity. Thismaybeaverygoodchoiceforthepersonwhoisn'tsure whethertheywanttocontinuewithXcodeandprogramming. Ifthat'sthecase,thendownloadthelatestversionofXcode
fromhttps://developer.apple.com/xcode/andmeetmeat
Figure1-13.
$99option:Ifyoudowanttorunyourappsonaphysical
Installing Xcode
Let'sgetstartedinstallingXcode.
1. Goto http://developer.apple.com/programs/ios/or
http://bit.ly/rrrdjc.You’llseeapagesimilartotheone
showninFigure1-4.ClicktheEnrollNowbutton.
Figure1-4.ClicktheEnrollNowbutton.
Figure1-5.ClicktheContinuebutton.
3. Mostpeoplereadingthisbookwillselectthe‘‘Ineedtocreatea
Figure1-6.Clickthe“Ineedtocreateanewaccount…”optiontoproceed.
4. Youareprobablygoingtobeenrollingasanindividual,soclick
Figure1-7.ClicktheIndividualoption.
5. EnterallyourinformationasshowninFigure1-8andpayyour
Figure1-8.Enterallyourinformationaccordingly.
NOTE:Beforeyoumoveontostep6,makesureyouhavereceivedyourconfirmation emailandchosenapasswordtocompletethelaststepofsettingyouupasabona fideregisteredAppledeveloper.Congratulations!
6. UseyourAppleIDtologintothemainiOSdevelopmentpage
athttp://developer.apple.com.Thispagehasthreeiconsfor
Figure1-9.FornowclickontheiOSDevCentericonasindicatedbythearrow.Lateryoumaywantto alsoprogramappsfortheMacComputerortheSafariWebBrowser.
7. Afterlogginginwithyourusernameandpasswordasdescribed
instep6,youwillseeascreensimilartoFigure1-10.TheiOS DevCentercontainsallthetoolsnecessarytobuildiOSapps. Lateronyouwillspendtimehere,butfornowjustgotothe DeveloperPageofthelatestbuildoftheiOSSDK.Clicktheicon indicatedbythearrow.
Figure1-10.TheDownloadslinktakesyoutothebottomofthepageasshowninFigure1-11.
NOTE:Atthetimeofwriting,Xcode4.3andiOSSDK5arethelatestenvironments. Thereisagreatchancethatbythetimeyoureadthisbookthesemayhavelarger numbers.Thisisnotaproblem—justgoontostep8.Ifbychancethereissomething thathasreallythrownusacurveball,itwillbediscussedandsolvedforyouinour forumlocatedatwww.rorylewis.com/ipad_forum/or
http://bit.ly/oLVwpY.
8. Fornowwewantyoutoclickonthelatestversion.Thefigures
Figure1-11.ClickingtheDownloadXcode4buttontakesyoutotheXcode4Developerpage.
9. ClicktheViewinMacAppStorebutton.Rememberthatifit’sa
Figure1-12.ClicktheViewinMacAppStorelink.
10. ClicktheInstallbutton,asshowninFigure1-13.Asthe
Figure1-13.ClickInstallandthenwaitforthedownloadtocomplete.
WithyourXcodeandiPhone/iPadSimulatortoolsinstalledandreadytoaccess easily,you’realmostreadytoroll.
ABOUTDEMOMONKEY
Beforeyouloadthefinaltool—calledDemoMonkey—let’sstepbackandhavealookatwhere we’regoing.
Getting Ready for Your First iPhone/iPad
Project
BeforestartingonyourfirstStoryboardingapp,youneedtomakesurethat everythingruns.Assumingyou’vealreadydownloadedandinstalledXcode, openupXcode.
1. PressCommand+Shift+N(N),simultaneously.Thiswill
openanewwindowthatshowcasesthedifferenttypesof projecttemplatesinthelandofXcode.
2. Figure1-14displaystheprojecttemplates:Master-Detail
Application,OpenGLGame,Page-BasedApplication,Single ViewApplication,TabbedApplication,UtilityApplication,and EmptyApplication.ClickSingleViewApplicationasshownin Figure1-14andthenclickNext.
Figure1-14.SelecttheSingleViewApplicationandthenclickNext.
3. OnyourscreenyoushouldseesomethingverysimilartoFigure
1-15.Firstcallyourprojecttestasindicatedbyarrow1.
Figure1-15.Let’sgoforatestdrive.
NOTE:ForthistestwearenotusingStoryboarding;wejustwanttoseethatXcode buildsasimpleapp.Sokeepeverythingunchecked—yes,including"Use
Storyboard"fornow(asshowninFigure1-15).
4. Figure1-16showstheinitialviewofXcode’sIDE.Clickthe
Figure1-16.TheinitialIntegratedDevelopmentEnvironment(IDE)screen.
5. ThiswillbringupthescreenshowninFigure1-17wherewe
Figure1-17.Runit!
6. TheiPhoneSimulatorpopsup,asillustratedinFigure1-18.
Congratulations!You'veloadedXcodeandyou'vetakenitforatestdrive.Now let'sgetDemoMonkeyrunningandstartStoryboarding.
Installing DemoMonkey
DemoMonkeyisanoptionaltoolintendedtohelpyoufollowalongwiththebook
projects.Youonlyneeditifyouchoosetouseour.demoMonkeyfilesforeach
chapter,whichwillallowyoutodraganddropready-to-usecodesnippetsinto theXcodeformostofthesteps.Otherwise,youcanstilltypethecodeyourself, andifyouchoosenottouseDemoMonkeyforthisbook,youcanskiptherest ofthischapter.
DemoMonkeywillmakelifeeasierforyouandletyoufocusmoreonthecode youa reu sing---butyouwillstillbechallengedinthisbook,andthat'ssimply partofourpedagogy.Theissueisreallyhowtohandlethingswhenyouget challenged.
NOTE:Whenyoudofindyourselfinoneofthosetoughspots,youcanalwaysreread thesection,rewindthevideoexamples,or—mostimportantly—govisittheforum wherethereareoftenmanypeople,includingus,onlineandreadytohelpyou immediately.Wemayreferyoutosomebodyelse'ssolutionorwemayhelpyou directly.Sogototheforum,say"hello"tothecrowd,andbecomeimmersedbyfirst seekinghelpfromothersandthengoingbacktohelpothersattheforum,locatedat www.rorylewis.com/ipad_forum/orhttp://bit.ly/oLVwpY.
WithyourXcoderunningandbuildingapps,youcannowinstallDemoMonkey.
1. AppleprovidesDemoMonkeyasanOSXsamplecodeproject
thatisavailablefordownloadtoanyone.Goto
http://developer.apple.com/library/mac/#samplecode/DemoMo
nkey/Introduction/Intro.htmlor http://bit.ly/v3BuKI,as
Figure1-19.DownloadSampleCode
2. Unzipthezipfilebydouble-clickingit,openthefolder,andthen
doubleclickontheDemoMonkey.xcodeprojfile,asindicatedby
Figure1-20.OpentheDemoMonkeyXcodeprojectinsideyourDemoMonkeyfolder.
3. Afterthe‘‘BuildSucceeded’’messageshowsup,expandthe
ProjectNavigator,right-clickontheDemoMonkey.appicon,and
Figure1-21.ExpandtheProjectNavigatorandchooseShowinFinderfromthecontextmenu.
4. Lastly,onceFinderopensthefoldercontainingtheapplication
youjustbuilt,dragtheDemoMonkey.apptoyourApplications
Figure1-22.DragtheDemoMonkey.apptoyourApplicationsfolder.
NOTE:Ifforsomereasonyouwereunabletoreproducethestepsinthissection,you candownloadacompiledDemoMonkey.appfromoursiteusingthislink:
www.rorylewis.com/docs/02_iPad_iPhone/Storyboarding%20Book/Stor yboarding%20Video%20Tutorials.html.Thensimplydragittoyour
Applicationsfolder.
2
Chapter
Fundamentals
WiththereleaseofiOS5,ApplehasgiveniOSdevelopersanupdatedSDKwith morethan1500APIs,amongwhichStoryboardingisoneofthemostintriguing. SowhatisStoryboarding?AndhowcanitmakeyourlifeasiOSdeveloper easier?
ForourintroductiontoStoryboarding,wewillnavigateourwaythroughthis awesomenewtool.Storyboardingallowsonetolayouttheworkflowofyour appusingthenewStoryboardsfeaturebuiltintothedesigntoolsofXcode. CreatedforappsthatuseNavigationandTabBarstotransitionbetweenViews, StoryboardseasethedevelopmentbymanagingtheViewControllersforyou. Youcanspecifythetransitionsandseguesthatareusedwhenswitching betweenViewswithouthavingtocodethembyhand.Storyboardingenables youtointeractseamlesslyandlinkallthescreensinyourapplicationwithoutthe cumbersomecodeyouhadtowriteforthetransitionsbetweenthescreensand thecontrolsusedtotriggerthetransitions.Thisallowsyoutoseeeverypossible paththroughyourapplicationgraphically,greatlyreducingtheamountofcode youneedtowriteforacomplexmulti-Viewapplication.
BeforewediveintoallthenutsandboltsofcreatingappsusingStoryboarding, let’stakeaquicktourofwhatliesbehindthisnewdevelopertool.
Asyoumayalreadyknow,sincethereleaseofXcode4,InterfaceBuilder(IB) hasbeencompletelyintegratedwithintheXcodeIDEsothereisnolongera separateapplicationforbuildingyouruserinterface(UI).Selectinganinterface
file(.nib/.xib)inyourprojectsimplyopenstheIBEditorwithinXcode,where
youtweakyourUIjustthewayyouwantit.
veryconvenientlygetanoverviewoftheapp.Itisverysimilartoa.nib/.xibfile exceptthatitmanagesmultipleViewControllersforyouandallowsyouto specifythetransitionsusedwhenswitchingfromoneViewtoanotherwithout havingtocodethemmanually.YoucanthinkofaStoryboardasacollectionof
mini.xibsandtransitionsand/orrelationshipsbetweenthem.
Withthebuilt-inStoryboardingfeature,youcannowlayouttheworkflowofyour appvisuallybeforewritinganycodeatall!Italsoreducestheamountofcode youneedtowriteforcomplexmultiscreenapplications.
Everwonderedwhatliesbehindthemysterious.storyboardfiles?Theanswer
mays urpriseyou:i t’sX ML( ExtensibleM arkupL anguage)---yes,goodol'XML that’ssowidelyusedinweb-servercommunicationandavarietyofweb applications.So,atthelowlevel,Storyboardisjustatextdocumentformatted inaspecialwaythatdefinesanobjectgraphofyourapplicationUI,andwhich iOSinterpretsatruntimetorendertheUIelements,basedontherulesspecified inthedocument.ThisXMLfilekeepstrackofalltheattributesforeveryUI elementintheStoryboardaswellastransitionsand/orrelationshipsbetween them.
Infact,youcancheckitoutforyourself.OpenXcodeandcreateanewproject. SelecttheSingleViewApplicationtemplateinthefirstdialogscreen.HitNext. Nametheprojectwhateveryoulike,butmakesuretheUseStoryboardsoption ischecked.Saveittoyourpreferredlocation.Oncethenewprojectopensup, you’llseethatXcodehascreatedafileforyoucalled
MainStoryboard.storyboard.SelectthefileintheProjectNavigatorasshownin
Figure2-0B.StoryboardfileviewedasXMLdocument
NowthatyouknowthesecretbehindtheStoryboardimplementation,let’stake aquickpeekathowitlooksatfirstsight.
Asyouprobablynoticed,thebasicStoryboardcreatedbytheXcodeforSingle
ViewApplicationtemplateisalmostidenticaltoanyregular.xibfileyoumay
haveseenbefore,withjustafewexceptions:there’sanincomingarrowpointing towardsthemainView,andthere’sablackcontainerbelowthemainViewthat says‘‘ViewController.’’Bothoftheseelementsserveaveryclearpurpose. BecauseStoryboardcanhavemultipleViewControllers,youneedawayto specifywhichoneofthoseshouldloadwhentheappstarts;thearrowis pointingtowardstheViewControllerthatwillbethefirstViewpresentedtothe userwhentheappislaunched.TochangetheInitialViewControllerofyour application,draganddropthearrowontoanyViewControllerintheStoryboard thatyouwanttobepresentedfirst.
NOTE:FirstResponderisaplaceholderobjectthatrepresentsthefirstobjectinthe responderchain,whichisdetermineddynamicallyatruntimebytheUIKitframework. Thisobjectfirstreceivesmanykindsofeventsliketouches,keyevents,action messages,andsoon.IniOSapplications,thereisnosingleFirstResponderobject— theFirstResponderisalwaystheViewthatisthetargetofatouch,whichistypically thecurrentlyselectedobjectortheobjectwiththecurrentfocusinthefrontmost window.
Figure2-0C.Scene’sDockwithFirstResponderandViewControllerobjects
We’llgiveyouashortoverviewofthemainhigh-levelconceptsyoushould understandbeforewestartStoryboardingapps.
Figure2-0D.Storyboards’Master-DetailApplicationtemplate
TherearetwomainconceptsinStoryboarding:sceneandsegue.
SceneisaViewControllerthateitherrepresentsascreenintheapporjustone majorcomponentarea(likeasplitViewpaneinaSplitViewController).Youcan doeverythinghereyouusedtodoinanibfile:dragandrearrangeUIelements (likelabels,textfields,andimages),resizethem,settheirpropertiesinthe AttributeInspector,andsoon.
SeguedefinesnavigationinyourStoryboard.Itindicateshowtogetfrompoint AtoB.Youusuallycreateaseguebypickinganeventsource(likeabuttonora tableViewcell)andchoosingascenetotransitionto.Youcanalsochoosethe typeofanimationyouwanttouse.AllApplebuilt-inanimationsareavailableto youbymakingasimpleselection.Additionally,youcanevencreateyourown customanimationsforcustomsegues.
Asaresult,youusesceneandseguetobuildyourapplicationUI.
YoustartwithaViewControllerobjectthatrepresentsyourfirstscene(theinitial ViewController).TogetViewControllersforyourStoryboard,youselectObjects andControllersfromtheObjectLibrary(justasyoudidwithallotherUI
elementsinnibfiles)anddragtheViewControllersyouneedontothe Storyboardcanvas.EachViewControlleralwaysmanagesasinglesceneof yourapp.
NOTE:OntheiPhone,eachscenerepresentsthecontentsofasinglescreen.For iPadapplications,ascreencanbecomposedofthecontentsofmorethanonescene (asinthecaseofaSplitViewController).
Oneofthemostimportantconceptsishowdataispassedaround.Hereisa veryclassicscenario:aMaster-Detailapplicationwhereyoudisplaysomedata inaTableView,andwhenusertapsonacell,aDetailViewispresentedthat displaysadditionalinformationabouttheselection.Inthiscaseyoumustsenda referencetotheselectedobjecttotheDetailViewsoitknowsexactlywhatto display.
StoryboardingcomeswithanAPIforthat.Amethodcalled
prepareForSegue:sender:oneveryUIViewController,anditisintendedtobe
overridden.Youcanwritecodeherethatwilltakeeffectwhenevereachsegue fires.
Figure2-0E.Storyboardinginuseintheprofessionalenvironment.
ToillustratethatStoryboardsareindeedusedquiteextensively,evenforlarge-scaleprojects,Figure2-0EshowsoneofnineStoryboard-basedprojectsbeing usedatoneoftheauthor’sclients.Thisfigureisindicativeofhow,evenatthe professionallevel,Storyboardsareheretostay.
Sowithoutfurtherado,let’sgetgoing.
helloAlien: A Quick Example Application
We’llstartbyintroducingyoutoourfourfundamentalconceptsof Storyboarding:
Easilycreatetransitionsbetweenviewswithlittleornocode.
PassinformationbackfromaSecondaryViewtoaMainView.
SendinformationtoaSecondaryViewfromaMainView.
Transitionbetweenviewswithuser-createdvisualeffects.
Inourexampleapplicationwedemonstratethesefourconceptsby
CreatingabuttonthatinvokesatransitionfromaMainViewto
PassingaYes/NovaluefromaSecondaryView(AlienView)to theMainView.
Sendinguser-enteredtexttotheSecondaryView(AlienView)
fromtheMainView.
Createacustomsegue(pronounced‘‘segway’’)which
implementsafade-out/fade-inbetweenthetwoviews.
Todothiswe’llwriteasimpleappthatasksanAlienwhetherhe’soutthere. GoingtotheSecondaryView,you’llseethereisaswitchthattheAliencan switcho n---if,ofcourse,theAlienexists.IftheAlienswitchestheswitchtothe onposition,whenyougobacktotheMainView,amessageappearssayinghe doesexist.YoucanthensaysomethingtotheAlien,andyou’llseethemessage outthereinouterAlienspaceintheSecondaryView.Lastly,you’llcreatea customseguethattransportsyoufromtheMainViewtotheSecondaryViewin abeautifulway.Solet’sgettoit!
Preliminaries
Asinallthechapters,wesupplyyouwithavideoofDr.Lewiswritingand runningthecodeexactlyasdescribedhereinthebook.Youcanalsodownload thecodethat’sfromthevideoandusedprecisely‘‘asis’’hereinthisbook.And youcandownloadtheDemoMonkeyfilesandimagesusedineachchapter.
Figure2-1.Videos,code,andfilesforthischapter
InFigure2-1,arrow1pointstoanimagefromthevideoofthischapter,located
athttp://bit.ly/tNKUij.Arrow2pointstoanXcodeiconthatlinkstothe
Xcodeofthischapter,locatedathttp://bit.ly/QSYAV6.Arrow3pointstoan
iconthatlinkstoallthefilesnecessaryforthischapter,includingtheimagesand
theDemoMonkeyfileslocatedathttp://bit.ly/Qxr16s.Ifyouneedmorehelp,
gototheforumhttp://bit.ly/oLVwpY.
Beforeyoustart,makesureyou’vedownloadedtheimagesandDemoMonkey
fileathttp://bit.ly/Qxr16s andthatyouhaveopenedthemuponyour
Step1: Create a Button That Segues to a
Secondary View
Figure2-2.StartaSingleViewApplication.
1. OpenXcodeandclick++N (FileNewProject),as
showninFigure2-2.SelectSingleViewApplicationandpress
Enter/Return.NameithelloAlien.We’veusedtheCompany
Identifiercom.apress.Youcannameyourswhateveryoulike,but
ifyoufeelthereisachanceyouwillneedtocompareyourcode
tooursatanytime,goaheadandnameitcom.apresslikeoursso
thattherewillbelesschanceofconfusion.Wewon’tuseaclass prefix.MakesuretoselectiPhoneandcheckbothUse
Figure2-3.Dragintheimages.
2. NavigatetoyourTargetSettingsbyclickingtheprojecticonat
therootoftheNavigationtreeanddragthetwoAlienicon
imagefilesnamediPhone 57.pngandiPhone4 114.pngintothe
iconboxes(Figure2-3).TheIPhone57imagegoesintothe
regulariconbox,andtheiPhone4 114imagegoesintothe
Retinabox.AlsodragtheAlien.pngandAlien Face.pngimage
filesintoyourSupporting Filesfolder.Makesuretocheck
Figure2-4.AlsodragtheiconsfromtherootfoldertotheSupportingFilesfolder.
3. OncethesefilesarecopiedintoyourSupporting Filesfolder,
dragtheiconimagefilesintoyourSupporting Filesfolderas
showninFigure2-4.DeselecttheLandscapeLeftand LandscapeRightimageswithintheSupportedDevice
Figure2-5.AddaNavigationController.
4. Tomakehandlingviewtransitionssimple,we’llletaNavigation
Controllercoordinatethetransitioningforus.Openthe StoryboardfilebygoingtotheProjectNavigatorpaneonthe
leftandclickMainStoryboard.storyboardtoopenit.It’sinthis
Figure2-6.AssignAlien.pngtotheMainView.
5. You’regoingtonamethecurrentViewtoView.Double-clickthe
centeroftheViewController’sNavigationBarandenterthe nameView.(You’llseethisnamebeingusedinbuttonscreated byt heN avigationC ontroller---youneedtoreturntothisview fromanotherviewwhenyourunthisapp.)Nowaddanimageto yourviewbydragginganImageViewontotheexistingView ControllerScene’scanvas.LetitautosizetothefullViewsize andcenteritintheViewasyoudragtheImageViewontothe
View.GototheAttributesInspectorandselectAlien.pngasthe
Figure2-7.AddabuttonandViewController.
6. Nextyouneedtoaddabuttontothissceneandaddanew
Figure2-8.ConnectthebuttontothenewViewController.
7. Younowneedtoperformoneofthecoolestthings
Figure2-9.SelectPush.
8. Onceyou’veControl-draggedovertothenewViewController,
Figure2-10.NamethenewViewControllerandsettheimage.
9. NamethissecondViewControllerAlienView.Todothis,asyou didwiththefirstview,double-clickthenewViewController’s NavigationBarandnameitAlienView.Whilewe’reherelet’s createtheAlien’sImageView.DraganImageViewontothe ViewController’scanvas.WiththeimageViewstillselected,in
AttributesInspectorselectAlien Face.pngasitsImage.Thisis
Figure2-11.Thesegueworks!NoCode!
10. Believeitornot,youalreadyhavearunningapp!Runitby
clickingtheRunbuttoninthetopleft-handcornerofXcode,and asshowninFigure2-11itworksbeautifully.Clickthebutton, andyougototheAlienView.Clickthebackbuttonentitled Viewontheleft-handsideoftheNavigationBarintheAlien View,andyoureturntotheMainView.Beautiful!
Step 2: Pass Information Back from a Secondary
View (Alien View) to the Main View
Figure2-12.DragalabelontotheMainView.
1. WhenpassingbackresultsfromtheAlienView,youneedsome
waytodisplaythefactthattheresultshavebeenreturned. You’regoingtoshowtextontheMainViewthatchangesbased onthevaluereturned.Addalabelwhereyoucanindicate whethertheAlienexists.DragalabelontotheMainViewunder thebutton.Centerit,setthetextcolortowhite,andenter
StatuswillappearhereintotheTextboxasshownin
Figure2-13.Control-dragfromtheLabeltoViewController.h.
2. Tobeabletosetthelabeltextfromourcode,youneedtohave
aconnectiontothisnewlabel.Let’screatetheLabel’sIBOutlet
(yourconnection).OpentheAssistant(itsiconisinthewhite circleinFigure2-13)andmakesureithascorrelatedthe
ViewController.hfileontotheright-handpaneoftheSplitView.
Control-dragfromthelabeltotheViewController.hfile,
droppingitdirectlyunderthe@interfaceViewControllerlineas
Figure2-14.Control-dragfromtheLabeltoViewController.h.
3. AfteryoudroptheconnectorintotheViewController.hfile,a
connectiondialogboxappears.Keepthisconnectiontypeasan
OutletandnameitlblFindStatus.(Thelblprefixremindsyou
Figure2-15.AddanewViewControllersubclass.
4. YounowneedtoaddcustomcodetotheViewControllerfor
yourAlienView.DothisbycreatinganewderivedView
Controllerclass.SelectthehelloAliengroupintheProject
Navigator(sothenewfilesareplacedwithinthisgroup).Press
+NandselecttheObjective-Cclassoptionasshownonthe
leftinFigure2-15.AfterclickingNext,namethenewclass
AlienViewController, selecttheUIViewControllersubclass
optionasshownontherightinFigure2-15,andclickNext. Don’tc hangea nyo ptions---savethem.Notethatthetwonew
files(AlienViewController.hand.m)wereplacedbelowthe
Supporting Filesgroup.Dragthembackabovethegroupso