1142 Beginning iOS Storyboarding free download ebook
BeginningiOS Storyboardingwith Xcode
EasilyDesignandDevelopYourApp,fromConcept andVisiontoCode
■ ■ ■ RoryLewis YuliaMcCarthy StephenM.Moraco
i
BeginningiOSStoryboardingwithXcode 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
precautionhasbeentakeninthepreparationofthiswork,neithertheauthor(s)norApressshallhaveany liabilitytoanypersonorentitywithrespecttoanylossordamagecausedorallegedtobecauseddirectly orindirectlybytheinformationcontainedinthiswork. Thesourcecodeforthisbookisavailabletoreadersatwww.apress.com.
ii
Tomymother,Adeline.Thankyouforthose13hours!Loveyou.
—Rory
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
toseeingwhereyougowithyourphotographypassionandthelifeaheadofyou.
—Stephen
iii
iv
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 ■
Chapter12:HowFarYou’veCome.............................................................. 609 ■ Index ........................................................................................................... 613
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
Chapter3:StoryboardingwithMapView ...................................................... 91 ■ flickrPhotoMap:ASingleViewApp..............................................................................92
Preliminaries ........................................................................................................................................................93 Step1:SettingUptheDataConnectionandDisplayingGeotaggedPhotosonaMap .........................................94 Step2:MakingaTransitiontoaSecondaryScenefromAnnotationCallouts ...................................................121 Step3:CreatingaModalScenethatAllowstheUsertoRateYourPhotos........................................................140
Chapter4:BuildingaUtilityApplication..................................................... 159 ■ utilityScales:AUtilityApp ..........................................................................................160
v
CONTENTS Preliminaries..............................................................................................................161 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 CodingtheAddBookViewController.................................................................................................................402 HookingUptheBooksScene .............................................................................................................................421 AddingCodefortheCategoriesScene...............................................................................................................442 ImplementingtheAuthorsScene .......................................................................................................................456 WrappingUpandLoadingTestData ..................................................................................................................470
Chapter9:SingleView##:wanderBoardPartI…...................................... 477 ■ wanderBoard:ASingle-ViewApp ..............................................................................477 Preliminaries..............................................................................................................480
HowWeCreatedour3DLandscape ...................................................................................................................481
vi
CONTENTS
vii
Step1:SetUptheFiles,ProjectSettings,andAssets...............................................483 Step2:PreptheStoryboard.......................................................................................483 ■ 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 ■ Index ........................................................................................................... 613
Foreword:AbouttheAuthors ThethreeauthorshavefoundabeautifulwaytoleadthebeginnerintoStoryboardingandatthe sametimeshowtheoldschoolcodersofObjective-Canewexquisitemethodologyforlearning anddebuggingthisincredibletool.Essentially,youhaveaguruofexplainingcomplexObjective- Ctobeginners,aformerAppleiOSintern,andasuper-successful,old-schoolcodershowing manypeoplefrommanydifferentwalksoflifethealphaandomegaofStoryboardcreation, debugging,andtweaking.
Dr.RoryLewis StephenM. YuliaMcCarthy Moraco Dr.RoryLewis RoryandImetinL.A.in1983.Heremindsmeofoneofmyfavoritefilmcharacters:Buckaroo Banzai—alwaysgoinginsixdirectionsatonce.Ifyoustophimandaskwhathe’sdoing,he’ll answercomprehensivelyandwithamazingdetail.Disciplined,colorful,andfriendly,hehasthe uncannyabilitytoexplainthehighlyabstractinsimple,organicterms.Healwaysaccomplishes whathesetsouttodo,andhe’llhelpyoudothesame.
viii
WhyYou’llRelatetoDr.Lewis
WhileattendingSyracuseUniversityasacomputer-engineeringstudent,Roryscrambledtopass hisclassesandmakeenoughmoneytosupporthiswifeandtwoyoungdaughters.In1990,he 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. Duringhissecondsummerinlawschool,Skjerven,Morrill,MacPherson,Franklin,& Friel—theotherfirmsharingtheworkontheAMDv.Intelcase—recruitedRorytoworkwith themattheirSiliconValleybranches(SanJoseandSanFrancisco).Afterimmersinghimselfin lawforseveralyearsandreceivinghisJDatSyracuse,Lewisrealizedhispassionwasforthe mathematicsofcomputers,notthelegalramificationsofhardwareandsoftware.Hepreferreda nurturingandcreativeenvironmentratherthanthefightingandarguingintrinsicinlaw. Afterthreeyearsawayfromacademia,RoryLewismovedsouthtopursuehisPhDin ComputerScienceattheUniversityofNorthCarolinaatCharlotte.There,hestudiedunderDr. ZbigniewW.Ras,knownworldwideforhisinnovationsindataminingalgorithmsandmethods, distributeddatamining,ontologies,andmultimediadatabases.WhilestudyingforhisPhD, Lewistaughtcomputersciencecoursestocomputerengineeringundergraduates,aswellase- commerceandprogrammingcoursestoMBAstudents.
ix
UponreceivinghisPhDinComputerScience,Roryacceptedatenure-trackpositionin ComputerScienceattheUniversityofColoradoatColoradoSprings,wherehisresearchisinthe computationalmathematicsofneurosciences.Mostrecently,heco-wroteagrantproposalonthe 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. AfterDr.Lewis’scoursehadbeensuccessfullypresented,andduringasubsequentconversationwitharepresentativefromApress,Lewishappenedtomentionthathe’donly
startedusingthatbookabouthalfwaythroughthesemester,ashehadtobringhisnon-
engineeringstudentsuptospeedfirst.Theeditorsuggestedconvertinghisnotesandoutlines intoaprimer—anintroductorybooktunedtotheless-technicalprogrammingcrowd.Atthat point,itwasonlyamatteroftimeanddetails—likeorganizingandrevisingDr.Lewis’spopular instructionalvideostomakethemavailabletoothernon-engineersexcitedtoprogramtheirown iPhoneand/oriPadapps. So,that’sthestoryofhowawackyprofessorcametowritethisbook.Wehopeyou’re inspiredtotakethishomeandbegin.Armyourselfwiththisknowledgeandbeginnowtochange yourlife! BenEaston Author,Teacher,Editor x
StephenM.Moraco
Stephenhasmorethan30yearsofexperienceinsoftwareengineering.He’sdevelopedprojects 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 programmingafterherinvaluableexperienceasaniOSAppsandFrameworksinternatApple’s headquartersinCupertino,Californiaduringthesummerof2011.Shebelievesthatlifeisall aboutconstantlyreachingfornewhorizonsandchallengingyourself.Asaprogrammer,this conceptisveryclosetoYulia’sheart. FromRussiatoUCDenvertoApple’siOSDivisionatCupertino,Yuliabelievesthat everythingispossibleifwefollowourdreams.
xi
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.
xii
AbouttheTechnicalReviewer MatthewKnott isaLearningPlatformdeveloperandSharePointexpert.Hehas beenprogrammingsinceayoungageandhasn’tstoppedlearningsince.An experiencedCandC#developer,MatthewhasrecentlystarteddevelopingiOS appstomobilizetheLearningPlatform.HelivesinWales,UnitedKingdom, withhiswifeandtwochildrenandlikestowriteonhisblog(mattknott.com) fromtimetotime.
xiii
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. WorkingwithStoryboardinginvolvesmuchmorethansimplydragginganddroppingViewControllersontoacanvas.Inthisbookweshowhowtostartfromscratchandbuild
completeappsusingStoryboarding.AlongthewaywedemonstrateusingcommoniOS
technologiesasMapViews,PageViewControllers,SplitViewControllers,CoreData,Table
Views,andmore—andwetellyouhowtheyallfittogetherwiththenewStoryboardingfeature. WhatYou’llLearn InChapter1,wehelpyoutogetstartediniOSdevelopmentbywalkingyouthroughApple’siOS DeveloperProgramregistrationprocessandinstallingXcodeandothertoolsyou’llbeusing throughoutthisbook. Chapter2talksaboutthebasicsofStoryboardstructureandintroducesthemainStoryboarding concepts,includingstandardviewtransitions,passinginformationaround,andcreatingcustom transitionsbetweentheviews. Chapter3explainshowtocreateamap-drivenappusingStoryboardingandhowtotransitionto otherscenesfromaMapView.ItalsodemonstratesseveralimportantStoryboardingconcepts, suchastriggeringmanualseguesandinstantiatingViewControllersdesignedintheStoryboardxiv
INTRODUCTION 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.