iOS Programming: The Big Nerd Ranch...

53

Transcript of iOS Programming: The Big Nerd Ranch...

Page 1: iOS Programming: The Big Nerd Ranch Guideptgmedia.pearsoncmg.com/images/9780134390734/samplepages/...iii Acknowledgments While our names appear on the cover, many people helped make
Page 2: iOS Programming: The Big Nerd Ranch Guideptgmedia.pearsoncmg.com/images/9780134390734/samplepages/...iii Acknowledgments While our names appear on the cover, many people helped make

iOS Programming: The Big Nerd Ranch Guideby Christian Keur and Aaron Hillegass

Copyright © 2015 Big Nerd Ranch, LLC

All rights reserved. Printed in the United States of America. This publication is protected by copyright, andpermission must be obtained from the publisher prior to any prohibited reproduction, storage in a retrieval system,or transmission in any form or by any means, electronic, mechanical, photocopying, recording, or likewise. Forinformation regarding permissions, contact

Big Nerd Ranch, LLC200 Arizona Ave NEAtlanta, GA 30307(770) 817-6373http://www.bignerdranch.com/[email protected]

The 10-gallon hat with propeller logo is a trademark of Big Nerd Ranch, LLC.

Exclusive worldwide distribution of the English edition of this book by

Pearson Technology Group800 East 96th StreetIndianapolis, IN 46240 USAhttp://www.informit.com

The authors and publisher have taken care in writing and printing this book but make no expressed or impliedwarranty of any kind and assume no responsibility for errors or omissions. No liability is assumed for incidentalor consequential damages in connection with or arising out of the use of the information or programs containedherein.

App Store, Apple, Cocoa, Cocoa Touch, Finder, Instruments, iCloud, iPad, iPhone, iPod, iPod touch, iTunes,Keychain, Mac, Mac OS, Multi-Touch, Objective-C, OS X, Quartz, Retina, Safari, and Xcode are trademarks ofApple, Inc., registered in the U.S. and other countries.

Many of the designations used by manufacturers and sellers to distinguish their products are claimed astrademarks. Where those designations appear in this book, and the publisher was aware of a trademark claim, thedesignations have been printed with initial capital letters or in all capitals.

ISBN-10  0134389379ISBN-13  978-0134389370

Fifth edition, first printing, December 2015Release D.5.1.1

Page 3: iOS Programming: The Big Nerd Ranch Guideptgmedia.pearsoncmg.com/images/9780134390734/samplepages/...iii Acknowledgments While our names appear on the cover, many people helped make

iii

AcknowledgmentsWhile our names appear on the cover, many people helped make this book a reality. We would like totake this chance to thank them.

• First and foremost we would like to thank Joe Conway for his work on the earlier editions of thisbook. He authored the first three editions and contributed greatly to the fourth edition as well.Many of the words in this book are still his, and for that, we are very grateful.

• A few people in particular went above and beyond with their help on this book. They are MikeyWard, Juan Pablo Claude, and Chris Morris.

• The other instructors who teach the iOS Bootcamp fed us with a never-ending stream ofsuggestions and corrections. They are Ben Scheirman, Bolot Kerimbaev, Brian Hardy, ChrisMorris, JJ Manton, John Gallagher, Jonathan Blocksom, Joseph Dixon, Juan Pablo Claude,Mark Dalrymple, Matt Bezark, Matt Mathias, Mike Zornek, Mikey Ward, Pouria Almassi, RodStrougo, Scott Ritchie, Step Christopher, Thomas Ward, TJ Usiyan, and Tom Harrington. Theseinstructors were often aided by their students in finding book errata, so many thanks are due to allthe students who attend the iOS Bootcamp.

• Thanks to all of the employees at Big Nerd Ranch who helped review the book, providedsuggestions, and found errata.

• Our tireless editor, Elizabeth Holaday, took our distracted mumblings and made them intoreadable prose.

• Anna Bentley jumped in to provide proofing.

• Ellie Volckhausen designed the cover. (The photo is of the bottom bracket of a bicycle frame.)

• Chris Loper at IntelligentEnglish.com designed and produced the print book and the EPUB andKindle versions.

• The amazing team at Pearson Technology Group patiently guided us through the business end ofbook publishing.

The final and most important thanks goes to our students whose questions inspired us to write thisbook and whose frustrations inspired us to make it clear and comprehensible.

Page 4: iOS Programming: The Big Nerd Ranch Guideptgmedia.pearsoncmg.com/images/9780134390734/samplepages/...iii Acknowledgments While our names appear on the cover, many people helped make

This page intentionally left blank

Page 5: iOS Programming: The Big Nerd Ranch Guideptgmedia.pearsoncmg.com/images/9780134390734/samplepages/...iii Acknowledgments While our names appear on the cover, many people helped make

v

Table of ContentsIntroduction ..................................................................................................................... xi

Prerequisites ............................................................................................................ xiWhat Has Changed in the Fifth Edition? ...................................................................... xiOur Teaching Philosophy .......................................................................................... xiiHow to Use This Book ............................................................................................ xiiiHow This Book Is Organized ................................................................................... xiiiStyle Choices .......................................................................................................... xvTypographical Conventions ........................................................................................ xvNecessary Hardware and Software .............................................................................. xv

1. A Simple iOS Application .............................................................................................. 1Creating an Xcode Project .......................................................................................... 2Model-View-Controller ............................................................................................... 5Designing Quiz ......................................................................................................... 6Interface Builder ....................................................................................................... 7Building the Interface ................................................................................................ 8

Creating view objects ......................................................................................... 9Configuring view objects .................................................................................. 11Running on the simulator .................................................................................. 12A brief introduction to Auto Layout ................................................................... 13Making connections ......................................................................................... 16

Creating the Model Layer ......................................................................................... 21Implementing action methods ............................................................................ 22Loading the first question ................................................................................. 22

Building the Finished Application .............................................................................. 23Application Icons .................................................................................................... 24Launch Screen ........................................................................................................ 26

2. The Swift Language ..................................................................................................... 27Types in Swift ........................................................................................................ 27Using Standard Types ............................................................................................... 28

Inferring types ................................................................................................ 30Specifying types .............................................................................................. 30Literals and subscripting ................................................................................... 32Initializers ...................................................................................................... 33Properties ....................................................................................................... 34Instance methods ............................................................................................. 34

Optionals ................................................................................................................ 34Subscripting dictionaries ................................................................................... 36

Loops and String Interpolation ................................................................................... 37Enumerations and the Switch Statement ...................................................................... 39

Enumerations and raw values ............................................................................. 40Exploring Apple’s Swift Documentation ...................................................................... 40

3. Views and the View Hierarchy ....................................................................................... 41View Basics ............................................................................................................ 42The View Hierarchy ................................................................................................. 42Creating a New Project ............................................................................................. 44

Page 6: iOS Programming: The Big Nerd Ranch Guideptgmedia.pearsoncmg.com/images/9780134390734/samplepages/...iii Acknowledgments While our names appear on the cover, many people helped make

iOS Programming

vi

Views and Frames ................................................................................................... 45Customizing the labels ..................................................................................... 53

The Auto Layout System .......................................................................................... 55Alignment rectangle and layout attributes ............................................................ 56Constraints ..................................................................................................... 57Adding constraints in Interface Builder ............................................................... 59Intrinsic content size ........................................................................................ 60Misplaced views .............................................................................................. 62Adding more constraints ................................................................................... 63

Bronze Challenge: More Auto Layout Practice ............................................................. 644. Text Input and Delegation ............................................................................................. 65

Text Editing ............................................................................................................ 65Keyboard attributes .......................................................................................... 68Responding to text field changes ........................................................................ 69Dismissing the keyboard ................................................................................... 72

Implementing the Temperature Conversion ................................................................... 73Number formatters ........................................................................................... 75

Delegation .............................................................................................................. 76Conforming to a protocol .................................................................................. 76Using a delegate .............................................................................................. 77More on protocols ........................................................................................... 79

Bronze Challenge: Disallow Alphabetic Characters ........................................................ 795. View Controllers .......................................................................................................... 81

The View of a View Controller .................................................................................. 82Setting the Initial View Controller .............................................................................. 82UITabBarController .................................................................................................. 85

Tab bar items .................................................................................................. 88Loaded and Appearing Views .................................................................................... 91

Accessing subviews ......................................................................................... 92Interacting with View Controllers and Their Views ........................................................ 92Silver Challenge: Dark Mode .................................................................................... 93For the More Curious: Retina Display ......................................................................... 93

6. Programmatic Views ..................................................................................................... 95Creating a View Programmatically ............................................................................. 97Programmatic Constraints ......................................................................................... 98

Anchors ......................................................................................................... 99Activating constraints ..................................................................................... 100Layout guides ................................................................................................ 101Margins ........................................................................................................ 102Explicit constraints ......................................................................................... 103

Programmatic Controls ........................................................................................... 104Bronze Challenge: Another Tab ................................................................................ 106Silver Challenge: User’s Location ............................................................................. 106Gold Challenge: Dropping Pins ................................................................................ 106For the More Curious: NSAutoresizingMaskLayoutConstraint ....................................... 107

7. Localization ............................................................................................................... 109Internationalization ................................................................................................. 110

Formatters .................................................................................................... 110

Page 7: iOS Programming: The Big Nerd Ranch Guideptgmedia.pearsoncmg.com/images/9780134390734/samplepages/...iii Acknowledgments While our names appear on the cover, many people helped make

iOS Programming

vii

Base internationalization ................................................................................. 113Preparing for localization ................................................................................ 114

Localization .......................................................................................................... 121NSLocalizedString and strings tables ................................................................. 124

Bronze Challenge: Another Localization .................................................................... 127For the More Curious: NSBundle’s Role in Internationalization ...................................... 127For the More Curious: Importing and Exporting as XLIFF ............................................ 128

8. Controlling Animations ............................................................................................... 129Basic Animations ................................................................................................... 130

Closures ....................................................................................................... 130Another Label ....................................................................................................... 132Animation Completion ............................................................................................ 135Animating Constraints ............................................................................................ 135Timing Functions ................................................................................................... 139Bronze Challenge: Spring Animations ....................................................................... 141Silver Challenge: Layout Guides .............................................................................. 141

9. UITableView and UITableViewController ....................................................................... 143Beginning the Homepwner Application ...................................................................... 143UITableViewController ........................................................................................... 145

Subclassing UITableViewController .................................................................. 146Creating the Item Class ........................................................................................... 147

Custom initializers ......................................................................................... 147UITableView’s Data Source ..................................................................................... 149

Giving the controller access to the store ............................................................. 150Implementing data source methods ................................................................... 152

UITableViewCells .................................................................................................. 153Creating and retrieving UITableViewCells .......................................................... 155Reusing UITableViewCells .............................................................................. 156

Content Insets ....................................................................................................... 158Bronze Challenge: Sections ..................................................................................... 159Silver Challenge: Constant Rows .............................................................................. 159Gold Challenge: Customizing the Table ..................................................................... 159

10. Editing UITableView ................................................................................................. 161Editing Mode ........................................................................................................ 161Adding Rows ........................................................................................................ 166Deleting Rows ....................................................................................................... 168Moving Rows ........................................................................................................ 169Displaying User Alerts ............................................................................................ 170Design Patterns ...................................................................................................... 174Bronze Challenge: Renaming the Delete Button .......................................................... 174Silver Challenge: Preventing Reordering .................................................................... 174Gold Challenge: Really Preventing Reordering ............................................................ 174

11. Subclassing UITableViewCell ..................................................................................... 175Creating ItemCell ................................................................................................... 176Exposing the Properties of ItemCell .......................................................................... 178Using ItemCell ...................................................................................................... 179Dynamic Cell Heights ............................................................................................ 180Dynamic Type ....................................................................................................... 181

Page 8: iOS Programming: The Big Nerd Ranch Guideptgmedia.pearsoncmg.com/images/9780134390734/samplepages/...iii Acknowledgments While our names appear on the cover, many people helped make

iOS Programming

viii

Responding to user changes ............................................................................. 184Bronze Challenge: Cell Colors ................................................................................. 184

12. Stack Views ............................................................................................................. 185Using UIStackView ................................................................................................ 187

Implicit constraints ......................................................................................... 188Stack view distribution .................................................................................... 191Nested stack views ......................................................................................... 192Stack view spacing ......................................................................................... 192

Segues ................................................................................................................. 194Hooking Up the Content ......................................................................................... 195Passing Data Around .............................................................................................. 200Bronze Challenge: More Stack Views ........................................................................ 201

13. UINavigationController .............................................................................................. 203UINavigationController ........................................................................................... 205Navigating with UINavigationController .................................................................... 209Appearing and Disappearing Views ........................................................................... 210Dismissing the Keyboard ......................................................................................... 211

Event handling basics ..................................................................................... 212Dismissing by pressing the Return key .............................................................. 213Dismissing by tapping elsewhere ...................................................................... 214

UINavigationBar .................................................................................................... 216Adding buttons to the navigation bar ................................................................. 218

Bronze Challenge: Displaying a Number Pad .............................................................. 220Silver Challenge: A Custom UITextField ................................................................... 220Gold Challenge: Pushing More View Controllers ......................................................... 220

14. Camera ................................................................................................................... 221Displaying Images and UIImageView ........................................................................ 222

Adding a camera button .................................................................................. 224Taking Pictures and UIImagePickerController ............................................................. 226

Setting the image picker’s sourceType ............................................................... 226Setting the image picker’s delegate ................................................................... 228Presenting the image picker modally ................................................................. 228Saving the image ........................................................................................... 230

Creating ImageStore ............................................................................................... 231Giving View Controllers Access to the Image Store ..................................................... 232Creating and Using Keys ......................................................................................... 233Wrapping Up ImageStore ........................................................................................ 236Bronze Challenge: Editing an Image ......................................................................... 237Silver Challenge: Removing an Image ....................................................................... 237Gold Challenge: Camera Overlay ............................................................................. 237For the More Curious: Navigating Implementation Files ............................................... 238

// MARK: ..................................................................................................... 23915. Saving, Loading, and Application States ....................................................................... 241

Archiving ............................................................................................................. 242Application Sandbox .............................................................................................. 245

Constructing a file URL .................................................................................. 247NSKeyedArchiver and NSKeyedUnarchiver ................................................................ 248

Loading files ................................................................................................. 251

Page 9: iOS Programming: The Big Nerd Ranch Guideptgmedia.pearsoncmg.com/images/9780134390734/samplepages/...iii Acknowledgments While our names appear on the cover, many people helped make

iOS Programming

ix

Application States and Transitions ............................................................................ 252Writing to the Filesystem with NSData ...................................................................... 254Error Handling ...................................................................................................... 257Bronze Challenge: PNG .......................................................................................... 259For the More Curious: Application State Transitions .................................................... 260For the More Curious: Reading and Writing to the Filesystem ....................................... 261For the More Curious: The Application Bundle ........................................................... 263

16. Size Classes ............................................................................................................. 265Another Size Class ................................................................................................. 266Bronze Challenge: Stacked Text Field and Labels ........................................................ 272

17. Touch Events and UIResponder .................................................................................. 273Touch Events ........................................................................................................ 274Creating the TouchTracker Application ...................................................................... 275Creating the Line Struct .......................................................................................... 276

Structs .......................................................................................................... 277Value types vs. reference types ......................................................................... 277

Creating DrawView ................................................................................................ 278Drawing with DrawView ......................................................................................... 279Turning Touches into Lines ..................................................................................... 280

Handling multiple touches ............................................................................... 281@IBInspectable ..................................................................................................... 286Silver Challenge: Colors ......................................................................................... 287Gold Challenge: Circles .......................................................................................... 287For the More Curious: The Responder Chain .............................................................. 288For the More Curious: UIControl ............................................................................. 289

18. UIGestureRecognizer and UIMenuController ................................................................. 291UIGestureRecognizer Subclasses .............................................................................. 292Detecting Taps with UITapGestureRecognizer ............................................................. 292Multiple Gesture Recognizers .................................................................................. 294UIMenuController .................................................................................................. 297More Gesture Recognizers ....................................................................................... 299

UILongPressGestureRecognizer ........................................................................ 299UIPanGestureRecognizer and simultaneous recognizers ........................................ 300

More on UIGestureRecognizer ................................................................................. 304Silver Challenge: Mysterious Lines ........................................................................... 305Gold Challenge: Speed and Size ............................................................................... 305Platinum Challenge: Colors ..................................................................................... 305For the More Curious: UIMenuController and UIResponderStandardEditActions ............... 306

19. Web Services ........................................................................................................... 307Starting the Photorama Application ........................................................................... 308Building the URL .................................................................................................. 309

Formatting URLs and requests ......................................................................... 309NSURLComponents ....................................................................................... 310

Sending the Request ............................................................................................... 314NSURLSession .............................................................................................. 314

Modeling the Photo ................................................................................................ 317JSON Data ........................................................................................................... 318

NSJSONSerialization ...................................................................................... 319

Page 10: iOS Programming: The Big Nerd Ranch Guideptgmedia.pearsoncmg.com/images/9780134390734/samplepages/...iii Acknowledgments While our names appear on the cover, many people helped make

iOS Programming

x

Enumerations and associated values .................................................................. 320Parsing JSON data ......................................................................................... 321

Downloading and Displaying the Image Data ............................................................. 327The Main Thread ................................................................................................... 330Bronze Challenge: Printing the Response Information .................................................. 331For the More Curious: HTTP ................................................................................... 331

20. Collection Views ...................................................................................................... 333Displaying the Grid ................................................................................................ 334Collection View Data Source ................................................................................... 335Customizing the Layout .......................................................................................... 338Creating a Custom UICollectionViewCell .................................................................. 341Downloading the Image Data ................................................................................... 345

Extensions .................................................................................................... 347Navigating to a Photo ............................................................................................. 350Silver Challenge: Updated Item Sizes ........................................................................ 352Gold Challenge: Creating a Custom Layout ................................................................ 352

21. Core Data ................................................................................................................ 353Object Graphs ....................................................................................................... 353Entities ................................................................................................................. 353

Modeling entities ........................................................................................... 354Transformable attributes .................................................................................. 356NSManagedObject and subclasses .................................................................... 356

Building the Core Data Stack ................................................................................... 358NSManagedObjectModel ................................................................................. 359NSPersistentStoreCoordinator ........................................................................... 359NSManagedObjectContext ............................................................................... 360

Updating Items ...................................................................................................... 361Inserting into the context ................................................................................. 361Saving changes .............................................................................................. 363

Updating the Data Source ....................................................................................... 364Fetch requests and predicates ........................................................................... 364

Saving Images to Disk ............................................................................................ 367Bronze Challenge: Photo View Count ........................................................................ 368

22. Core Data Relationships ............................................................................................ 369Relationships ......................................................................................................... 370Adding Tags to the Interface .................................................................................... 372Parent-Child Contexts ............................................................................................. 382Silver Challenge: Favorites ...................................................................................... 384

23. Afterword ................................................................................................................ 385What to Do Next ................................................................................................... 385Shameless Plugs .................................................................................................... 385

Index ........................................................................................................................... 387

Page 11: iOS Programming: The Big Nerd Ranch Guideptgmedia.pearsoncmg.com/images/9780134390734/samplepages/...iii Acknowledgments While our names appear on the cover, many people helped make

xi

IntroductionAs an aspiring iOS developer, you face three major tasks:

• You must learn the Swift language. Swift is the recommended development language for iOS. Thefirst two chapters of this book are designed to give you a working knowledge of Swift.

• You must master the big ideas. These include things like delegation, archiving, and the proper useof view controllers. The big ideas take a few days to understand. When you reach the halfwaypoint of this book, you will understand these big ideas.

• You must master the frameworks. The eventual goal is to know how to use every method of everyclass in every framework in iOS. This is a project for a lifetime: there are hundreds of classesand thousands of methods available in iOS, and Apple adds more classes and methods with everyrelease of iOS. In this book, you will be introduced to each of the subsystems that make up theiOS SDK, but you will not study each one deeply. Instead, our goal is to get you to the pointwhere you can search and understand Apple’s reference documentation.

We have used this material many times at our iOS bootcamps at Big Nerd Ranch. It is well tested andhas helped thousands of people become iOS developers. We sincerely hope that it proves useful to you.

PrerequisitesThis book assumes that you are already motivated to learn to write iOS apps. We will not spend anytime convincing you that the iPhone, iPad, and iPod touch are compelling pieces of technology.

We also assume that you have some experience programming and know something about object-oriented programming. If this is not true, you should probably start with Swift Programming: The BigNerd Ranch Guide.

What Has Changed in the Fifth Edition?All of the code in this book is Swift, and an early chapter is devoted to getting you up to speed withthis new language. Throughout the book, you will see how to use Swift’s capabilities and features towrite better iOS applications. We have come to love Swift at Big Nerd Ranch and believe you will, too.

Other additions include collection views and size classes and improved coverage of Auto Layout, webservices, and Core Data.

This edition assumes that the reader is using Xcode 7.1 or later and running applications on an iOS 9 orlater device.

Besides these obvious changes, we made thousands of tiny improvements that were inspired byquestions from our readers and our students. Every chapter of this book is just a little better than thecorresponding chapter from the fourth edition.

Page 12: iOS Programming: The Big Nerd Ranch Guideptgmedia.pearsoncmg.com/images/9780134390734/samplepages/...iii Acknowledgments While our names appear on the cover, many people helped make

Introduction

xii

Our Teaching PhilosophyThis book will teach you the essential concepts of iOS programming. At the same time, you will typein a lot of code and build a bunch of applications. By the end of the book, you will have knowledgeand experience. However, all the knowledge should not (and, in this book, will not) come first. That isthe traditional way we have all come to know and hate. Instead, we take a learn-while-doing approach.Development concepts and actual coding go together.

Here is what we have learned over the years of teaching iOS programming:

• We have learned what ideas people must grasp to get started programming, and we focus on thatsubset.

• We have learned that people learn best when these concepts are introduced as they are needed.

• We have learned that programming knowledge and experience grow best when they growtogether.

• We have learned that “going through the motions” is much more important than it sounds. Manytimes we will ask you to start typing in code before you understand it. We realize that you mayfeel like a trained monkey typing in a bunch of code that you do not fully grasp. But the best wayto learn coding is to find and fix your typos. Far from being a drag, this basic debugging is whereyou really learn the ins and outs of the code. That is why we encourage you to type in the codeyourself. You could just download it, but copying and pasting is not programming. We want betterfor you and your skills.

What does this mean for you, the reader? To learn this way takes some trust – and we appreciate yours.It also takes patience. As we lead you through these chapters, we will try to keep you comfortableand tell you what is happening. However, there will be times when you will have to take our wordfor it. (If you think this will bug you, keep reading – we have some ideas that might help.) Do not getdiscouraged if you run across a concept that you do not understand right away. Remember that we areintentionally not providing all the knowledge you will ever need all at once. If a concept seems unclear,we will likely discuss it in more detail later when it becomes necessary. And some things that are notclear at the beginning will suddenly make sense when you implement them the first (or the twelfth)time.

People learn differently. It is possible that you will love how we hand out concepts on an as-neededbasis. It is also possible that you will find it frustrating. In case of the latter, here are some options:

• Take a deep breath and wait it out. We will get there, and so will you.

• Check the index. We will let it slide if you look ahead and read through a more advanceddiscussion that occurs later in the book.

• Check the online Apple documentation. This is an essential developer tool, and you will wantplenty of practice using it. Consult it early and often.

• If Swift or object-oriented programming concepts are giving you a hard time (or if you think theywill), you might consider backing up and reading our Swift Programming: The Big Nerd RanchGuide.

Page 13: iOS Programming: The Big Nerd Ranch Guideptgmedia.pearsoncmg.com/images/9780134390734/samplepages/...iii Acknowledgments While our names appear on the cover, many people helped make

How to Use This Book

xiii

How to Use This BookThis book is based on the class we teach at Big Nerd Ranch. As such, it was designed to be consumedin a certain manner.

Set yourself a reasonable goal, like “I will do one chapter every day.” When you sit down to attacka chapter, find a quiet place where you will not be interrupted for at least an hour. Shut down youremail, your Twitter client, and your chat program. This is not a time for multitasking; you will need toconcentrate.

Do the actual programming. You can read through a chapter first, if you like. But the real learningcomes when you sit down and code as you go. You will not really understand the idea until you havewritten a program that uses it and, perhaps more importantly, debugged that program.

A couple of the exercises require supporting files. For example, in the first chapter you will need anicon for your Quiz application, and we have one for you. You can download the resources and solutionsto the exercises from http://www.bignerdranch.com/solutions/iOSProgramming5ed.zip.

There are two types of learning. When you learn about the Peloponnesian War, you are simply addingdetails to a scaffolding of ideas that you already understand. This is what we will call “Easy Learning.”Yes, learning about the Peloponnesian War can take a long time, but you are seldom flummoxed byit. Learning iOS programming, on the other hand, is “Hard Learning,” and you may find yourselfquite baffled at times, especially in the first few days. In writing this book, we have tried to create anexperience that will ease you over the bumps in the learning curve. Here are two things you can do tomake the journey easier:

• Find someone who already knows how to write iOS applications and will answer your questions.In particular, getting your application onto a device the first time is usually very frustrating if youare doing it without the help of an experienced developer.

• Get enough sleep. Sleepy people do not remember what they have learned.

How This Book Is OrganizedIn this book, each chapter addresses one or more ideas of iOS development through discussion andhands-on practice. For more coding practice, most chapters include challenge exercises. We encourageyou to take on at least some of these. They are excellent for firming up your grasp of the conceptsintroduced in the chapter and for making you a more confident iOS programmer. Finally, most chaptersconclude with one or two “For the More Curious” sections that explain certain consequences of theconcepts that were introduced earlier.

Chapter 1 introduces you to iOS programming as you build and deploy a tiny application. You will getyour feet wet with Xcode and the iOS simulator along with all the steps for creating projects and files.The chapter includes a discussion of Model-View-Controller and how it relates to iOS development.

Chapter 2 provides an overview of Swift, including basic syntax, types, optionals, initialization, andhow Swift is able to interact with the existing iOS frameworks. You will also get experience working ina playground, Xcode’s new code prototyping tool.

In Chapter 3, you will focus on the iOS user interface as you learn about views and the view hierarchyand create an application called WorldTrotter.

Page 14: iOS Programming: The Big Nerd Ranch Guideptgmedia.pearsoncmg.com/images/9780134390734/samplepages/...iii Acknowledgments While our names appear on the cover, many people helped make

Introduction

xiv

Chapter 4 introduces delegation, an important iOS design pattern. You will also a text field toWorldTrotter.

In Chapter 5, you will expand WorldTrotter and learn about using view controllers for managing userinterfaces. You will get practice working with views and view controllers as well as navigating betweenscreens using a tab bar.

In Chapter 6, you will learn how to manage views and view controllers in code. You will add asegmented control to WorldTrotter that will let you switch between various map types.

Chapter 7 introduces the concepts and techniques of internationalization and localization. You willlearn about NSLocale, strings tables, and NSBundle as you localize parts of WorldTrotter.

In Chapter 8, you will learn about and add different types of animations to the Quiz project that youcreated in Chapter 1.

Chapter 9 introduces the largest application in the book – Homepwner. (By the way, “Homepwner”is not a typo; you can find the definition of “pwn” at www.urbandictionary.com.) This applicationkeeps a record of your items in case of fire or other catastrophe. Homepwner will take eight chapters tocomplete.

In Chapter 9 - Chapter 11, you will work with tables. You will learn about table views, their viewcontrollers, and their data sources. You will learn how to display data in a table, how to allow the userto edit the table, and how to improve the interface.

Chapter 12 introduces stack views that will help you create complex interfaces very easily. You willuse a stack view to add a new screen to Homepwner that displays the details for a single item.

Chapter 13 builds on the navigation experience gained in Chapter 5. You will useUINavigationController to give Homepwner a drill-down interface and a navigation bar.

Chapter 14 introduces the camera. You will take pictures and display and store images in Homepwner.

In Chapter 15, you will add persistence to Homepwner using archiving to save and load the applicationdata.

In Chapter 16, you will learn about size classes, and you will use these to update Homepwner’sinterface to scale well across various screen sizes.

In Chapter 17 and Chapter 18, you will create a drawing application named TouchTrackerto learn about touch events. You will see how to add multitouch capability and how to useUIGestureRecognizer to respond to particular gestures. You will also get experience with the firstresponder and responder chain concepts and more practice with using structures and dictionaries.

Chapter 19 introduces web services as you create the Photorama application. This application fetchesand parses JSON from a server using NSURLSessions and NSJSONSerialization.

In Chapter 20, you will learn about collection views as you build an interface for Photorama usingUICollectionView and UICollectionViewCell.

In Chapter 21 and Chapter 22, you will add persistence to Photorama using Core Data. You will storeand load images and associated data using an NSManagedObjectContext.

Page 15: iOS Programming: The Big Nerd Ranch Guideptgmedia.pearsoncmg.com/images/9780134390734/samplepages/...iii Acknowledgments While our names appear on the cover, many people helped make

Style Choices

xv

Style ChoicesThis book contains a lot of code. We have attempted to make that code and the designs behind itexemplary. We have done our best to follow the idioms of the community, but at times we havewandered from what you might see in Apple’s sample code or code you might find in other books. Inparticular, you should know up-front that we nearly always start a project with the simplest templateproject: the single view application. When your app works, you will know it is because of your efforts– not because that behavior was built into the template.

Typographical ConventionsTo make this book easier to read, certain items appear in certain fonts. Classes, types, methods,and functions appear in a bold, fixed-width font. Classes and types start with capital letters, andmethods and functions start with lowercase letters. For example, “In the loadView() method of theRexViewController class, create a constant of type String.”

Variables, constants, and filenames appear in a fixed-width font but are not bold. So you will see, “InViewController.swift, add a variable named fido and initialize it to "Rufus".”

Application names, menu choices, and button names appear in a sans serif font. For example, “OpenXcode and select New Project... from the File menu. Select Single View Application and then clickChoose....”

All code blocks are in a fixed-width font. Code that you need to type in is always bold. For example, inthe following code, you would type in the two lines beginning @IBOutlet. The other lines are alreadyin the code and are included to let you know where to add the new lines.

import UIKit

class ViewController: UIViewController {

@IBOutlet var questionLabel: UILabel! @IBOutlet var answerLabel: UILabel!

}

Necessary Hardware and SoftwareTo build the applications in this book, you must have a Mac running OS X Yosemite (10.10.5) or later.You will also need Xcode, Apple’s Integrated Development Environment, which is available on theApp Store. Xcode includes the iOS SDK, the iOS simulator, and other development tools.

You should join the Apple Developer Program, which costs $99/year, because:

• Downloading the latest developer tools is free for members.

• You cannot put an app in the store until you are a member.

If you are going to take the time to work through this entire book, membership in the Apple DeveloperProgram is worth the cost. Go to http://developer.apple.com/programs/ios/ to join.

Page 16: iOS Programming: The Big Nerd Ranch Guideptgmedia.pearsoncmg.com/images/9780134390734/samplepages/...iii Acknowledgments While our names appear on the cover, many people helped make

Introduction

xvi

What about iOS devices? Most of the applications you will develop in the first half of the book are foriPhone, but you will be able to run them on an iPad. On the iPad screen, iPhone applications appear inan iPhone-sized window. Not a compelling use of iPad, but that is OK when you are starting with iOS.In the early chapters, you will be focused on learning the fundamentals of the iOS SDK, and these arethe same across iOS devices. Later in the book, you will see how to make applications run natively onboth iOS device families.

Excited yet? Good. Let’s get started.

Page 17: iOS Programming: The Big Nerd Ranch Guideptgmedia.pearsoncmg.com/images/9780134390734/samplepages/...iii Acknowledgments While our names appear on the cover, many people helped make

41

3Views and the View Hierarchy

Over the next five chapters, you are going to build an application named WorldTrotter. When it iscomplete, this app will convert values between degrees Fahrenheit and degrees Celsius. In this chapter,you will learn about views and the view hierarchy through creating WorldTrotter’s user interface. At theend of this chapter, your app will look like Figure 3.1.

Figure 3.1  WorldTrotter

Let’s start with a little bit of the theory behind views and the view hierarchy.

Page 18: iOS Programming: The Big Nerd Ranch Guideptgmedia.pearsoncmg.com/images/9780134390734/samplepages/...iii Acknowledgments While our names appear on the cover, many people helped make

Chapter 3  Views and the View Hierarchy

42

View BasicsRecall from Chapter 1 that views are objects that are visible to the user, like buttons, text fields, andsliders. View objects make up an application’s user interface. A view

• is an instance of UIView or one of its subclasses

• knows how to draw itself

• can handle events, like touches

• exists within a hierarchy of views whose root is the application’s window

Let’s look at the view hierarchy in greater detail.

The View HierarchyEvery application has a single instance of UIWindow that serves as the container for all the views in theapplication. UIWindow is a subclass of UIView, so the window is itself a view. The window is createdwhen the application launches. Once the window is created, other views can be added to it.

When a view is added to the window, it is said to be a subview of the window. Views that are subviewsof the window can also have subviews, and the result is a hierarchy of view objects with the window atits root (Figure 3.2).

Figure 3.2  An example view hierarchy and the interface that it creates

Page 19: iOS Programming: The Big Nerd Ranch Guideptgmedia.pearsoncmg.com/images/9780134390734/samplepages/...iii Acknowledgments While our names appear on the cover, many people helped make

The View Hierarchy

43

Once the view hierarchy is created, it will be drawn to the screen. This process can be broken into twosteps:

• Each view in the hierarchy, including the window, draws itself. It renders itself to its layer, whichyou can think of as a bitmap image. (The layer is an instance of CALayer.)

• The layers of all the views are composited together on the screen.

Figure 3.3 shows another example view hierarchy and the two drawing steps.

Figure 3.3  Views render themselves and then are composited together

For WorldTrotter, you are going to create an interface composed of different views. There will be fourinstances of UILabel and one instance of UITextField that will allow the user to enter in a temperaturein Fahrenheit. Let’s get started.

Page 20: iOS Programming: The Big Nerd Ranch Guideptgmedia.pearsoncmg.com/images/9780134390734/samplepages/...iii Acknowledgments While our names appear on the cover, many people helped make

Chapter 3  Views and the View Hierarchy

44

Creating a New ProjectIn Xcode, select File → New → Project... (or use the keyboard shortcut Command-Shift-N). From theiOS section, select Application, choose the Single View Application template, and click Next.

Enter WorldTrotter for the product name. Make sure that Swift is selected from the Language dropdownand that iPhone is selected from the Devices dropdown. Also make sure the Use Core Data box isunchecked (Figure 3.4). Click Next and then Create on the following screen.

Figure 3.4  Configuring WorldTrotter

Page 21: iOS Programming: The Big Nerd Ranch Guideptgmedia.pearsoncmg.com/images/9780134390734/samplepages/...iii Acknowledgments While our names appear on the cover, many people helped make

Views and Frames

45

Views and FramesWhen you initialize a view programmatically, you use its init(frame:) designated initializer. Thismethod takes one argument, a CGRect, that will become the view’s frame, a property on UIView.

var frame: CGRect

A view’s frame specifies the view’s size and its position relative to its superview. Because a view’s sizeis always specified by its frame, a view is always a rectangle.

A CGRect contains the members origin and size. The origin is a structure of type CGPoint andcontains two CGFloat properties: x and y. The size is a structure of type CGSize and has two CGFloatproperties: width and height (Figure 3.5).

Figure 3.5  CGRect

When the application is launched, the view for the initial view controller is added to the root-level window. This view controller is represented by the ViewController class defined inViewController.swift. We will discuss what a view controller is in Chapter 5, but for now, it issufficient to know that a view controller has a view and that the view associated with the main viewcontroller for the application is added as a subview of the window.

Before you create the views for WorldTrotter, you are going to add some practice viewsprogrammatically to explore views and their properties and see how the interfaces for applications arecreated.

Open ViewController.swift and delete any methods that the template created. Your file should looklike this:

import UIKit

class ViewController: UIViewController {

}

Page 22: iOS Programming: The Big Nerd Ranch Guideptgmedia.pearsoncmg.com/images/9780134390734/samplepages/...iii Acknowledgments While our names appear on the cover, many people helped make

Chapter 3  Views and the View Hierarchy

46

(Curious about the import UIKit line? UIKit is a framework. A framework is a collection of relatedclasses and resources. The UIKit framework defines many of the user interface elements that yourusers see, as well as other iOS-specific classes. You will be using a few different frameworks as you gothrough this book.)

Right after the view controller’s view is loaded into memory, its viewDidLoad() method is called. Thismethod gives you an opportunity to customize the view hierarchy, so it is a great place to add yourpractice views.

In ViewController.swift, override viewDidLoad(). Create a CGRect that will be the frame of aUIView. Next, create an instance of UIView and set its backgroundColor property to blue. Finally, addthe UIView as a subview of the view controller’s view to make it part of the view hierarchy. (Much ofthis will not look familiar. That is fine. We will explain more after you enter the code.)

class ViewController: UIViewController {

override func viewDidLoad() { super.viewDidLoad()

let firstFrame = CGRect(x: 160, y: 240, width: 100, height: 150) let firstView = UIView(frame: firstFrame) firstView.backgroundColor = UIColor.blueColor() view.addSubview(firstView) }

}

To create a CGRect, you use its initializer and pass in the values for origin.x, origin.y, size.width,and size.height.

To set the backgroundColor, you use the UIColor class method blueColor(). This is a conveniencemethod that initializes an instance of UIColor that is configured to be blue. There are a numberof UIColor convenience methods for common colors, such as greenColor(), blackColor(), andclearColor().

Page 23: iOS Programming: The Big Nerd Ranch Guideptgmedia.pearsoncmg.com/images/9780134390734/samplepages/...iii Acknowledgments While our names appear on the cover, many people helped make

Views and Frames

47

Build and run the application (Command-R). You will see a blue rectangle that is the instance ofUIView. Because the origin of the UIView’s frame is (160, 240), the rectangle’s top left corner is 160points to the right and 240 points down from the top left corner of its superview. The view stretches100 points to the right and 150 points down from its origin, in accordance with its frame’s size(Figure 3.6).

Figure 3.6  WorldTrotter with one UIView

Note that these values are in points, not pixels. If the values were in pixels, then they would not beconsistent across displays of different resolutions (i.e., Retina vs. non-Retina). A single point is arelative unit of a measure; it will be a different number of pixels depending on how many pixels are inthe display. Sizes, positions, lines, and curves are always described in points to allow for differences indisplay resolution.

Page 24: iOS Programming: The Big Nerd Ranch Guideptgmedia.pearsoncmg.com/images/9780134390734/samplepages/...iii Acknowledgments While our names appear on the cover, many people helped make

Chapter 3  Views and the View Hierarchy

48

Figure 3.7 represents the view hierarchy that you have created.

Figure 3.7  Current view hierarchy

Every instance of UIView has a superview property. When you add a view as a subview of anotherview, the inverse relationship is automatically established. In this case, the UIView’s superview is theUIWindow.

Let’s experiment with the view hierarchy. First, in ViewController.swift, create another instance ofUIView with a different frame and background color.

override func viewDidLoad() { super.viewDidLoad()

let firstFrame = CGRect(x: 160, y: 240, width: 100, height: 150) let firstView = UIView(frame: firstFrame) firstView.backgroundColor = UIColor.blueColor() view.addSubview(firstView)

let secondFrame = CGRect(x: 20, y: 30, width: 50, height: 50) let secondView = UIView(frame: secondFrame) secondView.backgroundColor = UIColor.greenColor() view.addSubview(secondView)}

Page 25: iOS Programming: The Big Nerd Ranch Guideptgmedia.pearsoncmg.com/images/9780134390734/samplepages/...iii Acknowledgments While our names appear on the cover, many people helped make

Views and Frames

49

Build and run again. In addition to the blue rectangle, you will see a green square near the top lefthandcorner of the window. Figure 3.8 shows the updated view hierarchy.

Figure 3.8  Updated view hierarchy with two subviews as siblings

Now you are going to adjust the view hierarchy so that one instance of UIView is a subview of the otherUIView instead of the view controller’s view. In ViewController.swift, add secondView as a subviewof firstView.

...

let secondView = UIView(frame: secondFrame)secondView.backgroundColor = UIColor.greenColor()

view.addSubview(secondView)firstView.addSubview(secondView)

Page 26: iOS Programming: The Big Nerd Ranch Guideptgmedia.pearsoncmg.com/images/9780134390734/samplepages/...iii Acknowledgments While our names appear on the cover, many people helped make

Chapter 3  Views and the View Hierarchy

50

Your view hierarchy is now four levels deep, as shown in Figure 3.9.

Figure 3.9  One UIView as a subview of the other

Build and run the application. Notice that secondView’s position on the screen has changed(Figure 3.10). A view’s frame is relative to its superview, so the top left corner of secondView is nowinset (20, 30) points from the top left corner of firstView.

Figure 3.10  WorldTrotter with new hierarchy

Page 27: iOS Programming: The Big Nerd Ranch Guideptgmedia.pearsoncmg.com/images/9780134390734/samplepages/...iii Acknowledgments While our names appear on the cover, many people helped make

Views and Frames

51

(If the green instance of UIView looks smaller than it did previously, that is just an optical illusion. Itssize has not changed.)

Now that you have seen the basics of views and the view hierarchy, you can start working on theinterface for WorldTrotter. Instead of building up the interface programmatically, you will use InterfaceBuilder to visually lay out the interface, as you did in Chapter 1.

In ViewController.swift, start by removing your practice code.

override func viewDidLoad() { super.viewDidLoad()

let firstFrame = CGRect(x: 160, y: 240, width: 100, height: 150) let firstView = UIView(frame: firstFrame) firstView.backgroundColor = UIColor.blueColor() view.addSubview(firstView)

let secondFrame = CGRect(x: 20, y: 30, width: 50, height: 50) let secondView = UIView(frame: secondFrame) secondView.backgroundColor = UIColor.greenColor() firstView.addSubview(secondView)}

Now let’s add some views to the interface and set their frames.

Open Main.storyboard. Notice that the interface on the screen is currently a square. While youexplore views and their frames, it will be nice to have the size of the interface in Xcode match thescreen size of the device that you will be using.

Select the View Controller either in the document outline or by clicking the yellow circle above theinterface. Open the attributes inspector, which is the fourth tab in the utilities area. You can quicklyopen this pane using the keyboard shortcut Command-Option-4.

At the top of the pane, find the section labeled Simulated Metrics and change the Size to be iPhone 4.7-inch. This will resize the square interface to match the dimensions of the 4.7-inch devices.

Page 28: iOS Programming: The Big Nerd Ranch Guideptgmedia.pearsoncmg.com/images/9780134390734/samplepages/...iii Acknowledgments While our names appear on the cover, many people helped make

Chapter 3  Views and the View Hierarchy

52

From the object library, drag five instances of UILabel onto the canvas. Space them out vertically onthe top half of the interface and center them horizontally. Set their text to match Figure 3.11.

Figure 3.11  Adding labels to the interface

Select the top label so you can see its frame in Interface Builder. Open its size inspector – the fifth tabin the utilities area. (As you might have noticed by this point, the keyboard shortcuts for the utilitiestabs are Command-Option plus the tab number. Since the size inspector is the fifth tab, its keyboardshortcut is Command-Option-5.)

Under the View section, find Frame Rectangle. (If you do not see it, you might need to select it fromthe Show pop-up menu.) These values are the view’s frame, and they dictate the position of the viewon screen (Figure 3.12).

Figure 3.12  View frame values

Page 29: iOS Programming: The Big Nerd Ranch Guideptgmedia.pearsoncmg.com/images/9780134390734/samplepages/...iii Acknowledgments While our names appear on the cover, many people helped make

Customizing the labels

53

Build and run the application on the iPhone 6s simulator. This corresponds to the 4.7-inch simulatedmetrics that you specified in the storyboard. The interface on the simulator will look identical to theinterface that you laid out in Interface Builder.

Customizing the labelsLet’s make the interface look a little bit better by customizing the view properties.

In Main.storyboard, select the background view. Open the attributes inspector and give the app a newbackground color: Find and click the Background dropdown and click Other. Select the second tab (theColor Sliders tab) and enter a Hex Color # of F5F4F1 (Figure 3.13). This will give the background awarm, gray color.

Figure 3.13  Changing the background color

You can customize attributes common to selected views simultaneously. You will use this to give manyof the labels a larger font size as well as a burnt orange text color.

Select the top two and bottom two labels by Command-clicking them in the document outline and openthe attributes inspector. Update the text color: Under the Label section, find Color and open the pop-upmenu. Select the Color Sliders tab again and enter a Hex Color # of E15829.

Page 30: iOS Programming: The Big Nerd Ranch Guideptgmedia.pearsoncmg.com/images/9780134390734/samplepages/...iii Acknowledgments While our names appear on the cover, many people helped make

Chapter 3  Views and the View Hierarchy

54

Now let’s update the font. Select the 212 and 100 labels. Under the Label section in the attributesinspector, find Font and click on the text icon next to the current font. From the popover that appears,make the Font System - System and the Size 70 (Figure 3.14). Select the remaining three labels. Opentheir Font pop-up and make the Font System - System and the Size 36.

Figure 3.14  Customizing the labels’ font

Now that the font size is larger, the text no longer fits within the bounds of the label. You could resizethe labels manually, but there is an easier way.

Select the top label on the canvas. From Xcode’s Editor menu, select Size to Fit Content (Command-=).This will resize the label to exactly fit its text contents. Repeat the process for the other four labels.(You can select all four labels to resize them all at once.) Now move the labels so that they are againnicely aligned vertically and centered horizontally (Figure 3.15).

Page 31: iOS Programming: The Big Nerd Ranch Guideptgmedia.pearsoncmg.com/images/9780134390734/samplepages/...iii Acknowledgments While our names appear on the cover, many people helped make

The Auto Layout System

55

Figure 3.15  Updating the label frames

Build and run the application on the iPhone 6s simulator. Now build and run the application on theiPhone 6s Plus simulator. Notice that the labels are no longer centered – instead, they appear shiftedslightly to the left.

You have just seen two of the major problems with absolute frames. First, when the contents change(like when you changed the font size), the frames do not automatically update. Second, the view doesnot look equally good on different sizes of screens.

In general, you should not use absolute frames for your views. Instead, you should use Auto Layout toflexibly compute the frames for you based on constraints that you specify for each view. For example,what you really want for WorldTrotter is for the labels to remain the same distance from the top of thescreen and to remain horizontally centered within their superview. They should also update if the fontor text of the labels change. This is what you will accomplish in the next section.

The Auto Layout SystemBefore you can fix the labels to have them lay out flexibly, you need to learn a little theory about theAuto Layout system.

As you saw in Chapter 1, absolute coordinates make your layout fragile because they assume that youknow the size of the screen ahead of time.

Page 32: iOS Programming: The Big Nerd Ranch Guideptgmedia.pearsoncmg.com/images/9780134390734/samplepages/...iii Acknowledgments While our names appear on the cover, many people helped make

Chapter 3  Views and the View Hierarchy

56

Using Auto Layout, you can describe the layout of your views in a relative way that enables theirframes to be determined at runtime so that the frames’ definitions can take into account the screen sizeof the device that the application is running on.

Alignment rectangle and layout attributesThe Auto Layout system is based on the alignment rectangle. This rectangle is defined by severallayout attributes (Figure 3.16).

Figure 3.16  Layout attributes defining an alignment rectangle of a view

Width/Height These values determine the alignment rectangle’s size.

Top/Bottom/Left/Right These values determine the spacing between the given edge of thealignment rectangle and the alignment rectangle of another view inthe hierarchy.

CenterX/CenterY These values determine the center point of the alignmentrectangle.

Baseline This value is the same as the bottom attribute for most, but notall, views. For example, UITextField defines its baseline asthe bottom of the text it displays rather than the bottom of thealignment rectangle. This keeps “descenders” (letters like ‘g’ and‘p’ that descend below the baseline) from being obscured by aview right below the text field.

Leading/Trailing These values are language-specific attributes. If the device is set toa language that reads left to right (e.g., English), then the leadingattribute is the same as the left attribute and the trailing attributeis the same as the right attribute. If the language reads right toleft (e.g., Arabic), then the leading attribute is on the right andthe trailing attribute is on the left. Interface Builder automaticallyprefers leading and trailing over left and right, and, in general, youshould as well.

Page 33: iOS Programming: The Big Nerd Ranch Guideptgmedia.pearsoncmg.com/images/9780134390734/samplepages/...iii Acknowledgments While our names appear on the cover, many people helped make

Constraints

57

By default, every view has an alignment rectangle, and every view hierarchy uses Auto Layout.

The alignment rectangle is very similar to the frame. In fact, these two rectangles are often the same.Whereas the frame encompasses the entire view, the alignment rectangle only encompasses the contentthat you wish to use for alignment purposes. Figure 3.17 shows an example where the frame and thealignment rectangle are different.

Figure 3.17  Frame vs. alignment rectangle

You cannot define a view’s alignment rectangle directly. You do not have enough information (likescreen size) to do that. Instead, you provide a set of constraints. Taken together, these constraintsenable the system to determine the layout attributes, and thus the alignment rectangle, for each view inthe view hierarchy.

ConstraintsA constraint defines a specific relationship in a view hierarchy that can be used to determine a layoutattribute for one or more views. For example, you might add a constraint like, “The vertical spacebetween these two views should always be 8 points,” or, “These views must always have the samewidth.” A constraint can also be used to give a view a fixed size, like, “This view’s height shouldalways be 44 points.”

You do not need a constraint for every layout attribute. Some values may come directly from aconstraint; others will be computed by the values of related layout attributes. For example, if a view’sconstraints set its left edge and its width, then the right edge is already determined (left edge + width= right edge, always). As a general rule of thumb, you need at least two constraints per dimension(horizontal and vertical).

If, after all of the constraints have been considered, there is still an ambiguous or missing value fora layout attribute, then there will be errors and warnings from Auto Layout and your interface willnot look as you expect on all devices. Debugging these problems is important, and you will get somepractice later in this chapter.

How do you come up with constraints? Let’s see how using the labels that you have laid out on thecanvas.

First, describe what you want the view to look like independent of screen size. For example, you mightsay that you want the top label to be:

• 8 points from the top of the screen• centered horizontally in its superview• as wide and as tall as its text

Page 34: iOS Programming: The Big Nerd Ranch Guideptgmedia.pearsoncmg.com/images/9780134390734/samplepages/...iii Acknowledgments While our names appear on the cover, many people helped make

Chapter 3  Views and the View Hierarchy

58

To turn this description into constraints in Interface Builder, it will help to understand how to find aview’s nearest neighbor. The nearest neighbor is the closest sibling view in the specified direction(Figure 3.18).

Figure 3.18  Nearest neighbor

If a view does not have any siblings in the specified direction, then the nearest neighbor is itssuperview, also known as its container.

Now you can spell out the constraints for the label:

1. The label’s top edge should be 8 points away from its nearest neighbor (which is its container –the view of the ViewController).

2. The label’s center should be the same as its superview’s center.

3. The label’s width should be equal to the width of its text rendered at its font size.

4. The label’s height should be equal to the height of its text rendered at its font size.

If you consider the first and fourth constraints, you can see that there is no need to explicitly constrainthe label’s bottom edge. It will be determined from the constraints on the label’s top edge and thelabel’s height. Similarly, the second and third constraints together determine the label’s right and leftedges.

Now that you have a plan for the top label, you can add these constraints. Constraints can be addedusing Interface Builder or in code. Apple recommends that you add constraints using InterfaceBuilder whenever possible, and that is what you will do here. However, if your views are created and

Page 35: iOS Programming: The Big Nerd Ranch Guideptgmedia.pearsoncmg.com/images/9780134390734/samplepages/...iii Acknowledgments While our names appear on the cover, many people helped make

Adding constraints in Interface Builder

59

configured programmatically, then you can add constraints in code. In Chapter 6, you will practice thatapproach.

Adding constraints in Interface BuilderLet’s get started constraining that top label.

Select the top label on the canvas. In the bottom righthand corner of the canvas, find the Auto Layoutconstraint menu (Figure 3.19).

Figure 3.19  Using the Auto Layout constraint menu

Click the icon (the third from the left) to reveal the Pin menu. This menu shows you the current sizeand position of the label.

At the top of the Pin menu are four values that describe the label’s current spacing from its nearestneighbor on the canvas. For this label, you are only interested in the top value.

To turn this value into a constraint, click the top red strut separating the value from the square in themiddle. The strut will become a solid red line.

In the middle of the menu, find the label’s Width and Height. The values next to Width and Heightindicate the current canvas values. To constrain the label’s width and height to the current canvasvalues, check the boxes next to Width and Height. The button at the bottom of the menu reads Add 3Constraints. Click this button.

Page 36: iOS Programming: The Big Nerd Ranch Guideptgmedia.pearsoncmg.com/images/9780134390734/samplepages/...iii Acknowledgments While our names appear on the cover, many people helped make

Chapter 3  Views and the View Hierarchy

60

At this point, you have not specified enough constraints to fully determine the alignment rectangle.Interface Builder will help you determine what the problem is.

In the top right corner of Interface Builder, notice the yellow warning sign (Figure 3.20). Click on thisicon to reveal the issue: “Horizontal position is ambiguous for "212".”

Figure 3.20  Horizontal ambiguity

You have added two vertical constraints (a top edge constraint and a height constraint), but youhave only added one horizontal constraint (a width constraint). Having only one constraint makesthe horizontal position of the label ambiguous. You will fix this issue by adding a center alignmentconstraint between the label and its superview.

With the top label still selected, click the icon (the second from the left in the Auto Layoutconstraints menu) to reveal the Align menu. If you have multiple views selected, this menu will allowyou to align attributes among the views. Since you have only selected one label, the only options youare given are to align the view within its container.

In the Align menu, select Horizontally in Container (do not click Add 1 Constraint yet). Once you addthis constraint, there will be enough constraints to fully determine the alignment rectangle. To ensurethat the frame of the label matches the constraints specified, open the Update Frames pop-up menufrom the Align menu and select Items of New Constraints. This will reposition the label to match theconstraints that have been added. Now click on Add 1 Constraint to add the centering constraint andreposition the label.

The label’s constraints are all blue now that the alignment rectangle for the label is fully specified.Additionally, the warning at the top right corner of Interface Builder is now gone.

Build and run the application on the iPhone 6s simulator and the iPhone 6s Plus simulator. The toplabel will remain centered in both simulators.

Intrinsic content sizeAlthough the top label’s position is flexible, its size is not. This is because you have added explicitwidth and height constraints to the label. If the text or font were to change, you would be in the sameposition you were in earlier. The size of the frame is absolute, so the frame would not hug to thecontent.

This is where the intrinsic content size of a view comes into play. You can think of the intrinsic contentsize as the size that a view “wants” to naturally be. For labels, this size is the size of the text renderedat the given font. For images, this is the size of the image itself.

A view’s intrinsic content size acts as implicit width and height constraints. If you do not specifyconstraints that explicitly determine the width, the view will be its intrinsic width. The same goes forthe height.

Page 37: iOS Programming: The Big Nerd Ranch Guideptgmedia.pearsoncmg.com/images/9780134390734/samplepages/...iii Acknowledgments While our names appear on the cover, many people helped make

Intrinsic content size

61

With this knowledge, let the top label have a flexible size by removing the explicit width and heightconstraints.

In Main.storyboard, select the width constraint on the label. You can do this by clicking on theconstraint on the canvas. Alternatively, in the document outline, you can click on the disclosure trianglenext to the 212 label, then disclose the list of constraints for the label (Figure 3.21). Once you haveselected the width constraint, press the Delete key. Do the same for the height constraint.

Figure 3.21  Selecting the width constraint

Notice that the constraints for the label are still blue. Since the width and height are being inferredfrom the label’s intrinsic content size, there are still enough constraints to determine the label’salignment rectangle.

Page 38: iOS Programming: The Big Nerd Ranch Guideptgmedia.pearsoncmg.com/images/9780134390734/samplepages/...iii Acknowledgments While our names appear on the cover, many people helped make

Chapter 3  Views and the View Hierarchy

62

Misplaced viewsAs you have seen, blue constraints indicate that the alignment rectangle for a view is fully specified.Orange constraints often indicate a misplaced view. This means that the frame for the view in InterfaceBuilder is different than the frame that Auto Layout has computed.

A misplaced view is very easy to fix. That is good, because it is also a very common issue that you willencounter when working with Auto Layout.

Give your top label a misplaced view so that you can see how to resolve this issue. Resize the top labelon the canvas using the resize controls and look for the yellow warning in the top right corner of thecanvas. Click on this warning icon to reveal the problem: “Frame for "212" will be different at runtime” (Figure 3.22).

Figure 3.22  Misplaced view warning

As the warning says, the frame at runtime will not be the same as the frame specified on the canvas. Ifyou look closely, you will see an orange dotted line that indicates what the runtime frame will be.

Build and run the application. Notice that the label is still centered despite the new frame that yougave it in Interface Builder. This might seem great – you get the result that you want, after all. But thedisconnect between what you have specified in Interface Builder and the constraints computed by AutoLayout will cause problems down the line as you continue to build your views. Let’s fix the misplacedview.

Back in the storyboard, select the top label on the canvas. Click the icon (the right-most icon) toreveal the Resolve Auto Layout Issues menu. Select Update Frames from the Selected Views section.This will update the frame of the label to match the frame that the constraints will compute.

You will get very used to updating the frames of views as you work with Auto Layout. One word ofcaution: if you try to update the frames for a view that does not have enough constraints, you willalmost certainly get unexpected results. If that happens, undo the change and inspect the constraints tosee what is missing.

At this point, the top label is in good shape. It has enough constraints to determine its alignmentrectangle, and the view is laying out the way you want.

Becoming proficient with Auto Layout takes a lot of experience, so in the next section you are going toremove the constraints from the top label and then add constraints to all of the labels.

Page 39: iOS Programming: The Big Nerd Ranch Guideptgmedia.pearsoncmg.com/images/9780134390734/samplepages/...iii Acknowledgments While our names appear on the cover, many people helped make

Adding more constraints

63

Adding more constraintsLet’s flesh out the constraints for the rest of the views. Before you do that, you will first remove theexisting constraints from the top label.

Select the top label on the canvas. Open the Resolve Auto Layout Issues menu and select ClearConstraints from the Selected Views section (Figure 3.23).

Figure 3.23  Clearing constraints

You are going to add the constraints to all of the views in two steps. First you will center the top labelhorizontally within the superview. Then you will add constraints that pin the top of each label to itsnearest neighbor while aligning the centers of all of the labels.

Select the top label. Open the Align menu and choose Horizontally in Container with a constant of 0.Make sure that Update Frames has None selected; remember that you do not want to update the frameof a view that does not have enough constraints, and this one constraint will certainly not provideenough information to compute the alignment rectangle. Go ahead and Add 1 Constraint.

Now select all five labels on the canvas. It can be very convenient to add constraints to multiple viewssimultaneously. Open the Pin menu and make the follow choices:

1. Select the top strut and make sure it has a constant of 8.

2. From the Align menu, choose Horizontal Centers.

3. From the Update Frames menu, choose Items of New Constraints.

Page 40: iOS Programming: The Big Nerd Ranch Guideptgmedia.pearsoncmg.com/images/9780134390734/samplepages/...iii Acknowledgments While our names appear on the cover, many people helped make

Chapter 3  Views and the View Hierarchy

64

Your menu should match Figure 3.24. Once it does, click Add 9 Constraints. This will add theconstraints to the views and update their frames to reflect the Auto Layout changes.

Figure 3.24  Adding more constraints with the Pin menu

Build and run the application on the iPhone 6s simulator. The views will be centered within theinterface. Now build and run the application on the iPhone 6s Plus simulator. Unlike earlier in thechapter, all of the labels remain centered on the larger interface.

Auto Layout is a crucial technology for every iOS developer. It helps you create flexible layouts thatwork across a range of devices and interface sizes. It also takes a lot of practice to master. You will geta lot of experience working with Auto Layout as you work through this book.

Now that the interface for WorldTrotter is using Auto Layout to adapt to various screen sizes, there isno need for you to specify an iPhone screen size when working in the storyboard.

In Main.storyboard, select the View Controller and open its attributes inspector. Find the SimulatedMetrics section and change the Size to Inferred. The interface updates to be the square shape that it wasinitially. Notice that the labels still remain centered in this square interface due to the constraints thatyou added.

Designing interfaces using the inferred square shape helps to force you to think about designingadaptive interfaces that work with a variety of screen sizes instead of designing for one particularscreen size.

Bronze Challenge: More Auto Layout PracticeRemove all of the constraints from the ViewController interface and then add them back in. Try to dothis without consulting the book.

Page 41: iOS Programming: The Big Nerd Ranch Guideptgmedia.pearsoncmg.com/images/9780134390734/samplepages/...iii Acknowledgments While our names appear on the cover, many people helped make

This page intentionally left blank

Page 42: iOS Programming: The Big Nerd Ranch Guideptgmedia.pearsoncmg.com/images/9780134390734/samplepages/...iii Acknowledgments While our names appear on the cover, many people helped make

387

IndexSymbols.xcassets (asset catalog), 24.xcdatamodeld (data model file), 354// MARK:, 239, 240@IBInspectable, 286

Aaccess control, 311accessory indicator (UITableViewCell), 153action methods

connecting in interface file, 226defining, 18implementing, 22and UIControl, 289

active state, 252addSubview(_:), 49alerts, displaying, 170-173alignment rectangles, 56, 57anchors, 99animateWithDuration:animations:, 130-132animations

animating constraints, 135-139basic, 130-132marking completion of, 135spring-like, 141timing functions, 139, 140

anti-aliasing, 93API Reference, 244append(_:), 34application bundle

explained, 263, 264and internationalization, 113, 127

application sandbox, 245-247, 263application states, 252-254, 260, 261applicationDidBecomeActive:, 254, 260applicationDidEnterBackground(_:), 248, 260applicationDidEnterBackground:, 254applications

(see also application bundle, debugging,projects)building, 12, 123cleaning, 123data storage, 246, 247directories in, 246, 247

icons for, 24, 25launch images for, 26multiple threads in, 330running on iPad, 3running on simulator, 12

applicationWillEnterForeground:, 254, 260applicationWillResignActive:, 254, 260archiving

vs. Core Data, 353described, 242implementing, 242-245with NSKeyedArchiver, 248-251

arraysabout, 31, 32append(_:), 34count, 34reverse(), 34subscripting, 32and traps, 32writing to filesystem, 261

asset catalogs (Xcode), 24assistant editor (Xcode), 226attributes (Core Data), 354Auto Layout

(see also constraints, Interface Builder)alignment rectangles, 56, 57autoresizing masks and, 107, 108dynamic cell heights, 180introduction to, 13-15layout attributes, 56, 57purpose of, 55

autoresizing masks, 98, 107, 108awakeFromInsert, 358

Bbackground state, 252-254, 260, 261Base internationalization, 113baselines, 56basic animations, 130-132becomeFirstResponder, 72Bool, 31boolean types, 31bundles

application (see application bundle)NSBundle, 127, 263

buttonsadding to navigation bars, 218

Page 43: iOS Programming: The Big Nerd Ranch Guideptgmedia.pearsoncmg.com/images/9780134390734/samplepages/...iii Acknowledgments While our names appear on the cover, many people helped make

Index

388

camera, 224

CCALayer, 43callbacks, 76

(see also delegation, target-action pairs)camera

(see also images)taking pictures, 224-230

cancelsTouchesInView, 300canPerformAction(_:withSender:), 306cells

(see also UITableViewCell)adding padding to, 158changing cell class, 177customizing layout of, 338dynamic cell heights, 180prototype, 157, 342reusing, 158

CGPoint, 45CGRect, 45-47CGSize, 45closures, 130-132, 247collection view

customizing layout of, 338displaying, 334downloading image data, 345-347layout object, 333navigating to/displaying photos, 350-352setting data source, 335-338

colorsbackground, 46, 335customizing, 53

common ancestor, 100concurrency, 330conditionals

if-let, 36switch, 39

connections (in Interface Builder), 16-20connections inspector, 20console

printing to, 78viewing in playground, 35

constants, 29constraints (Auto Layout)

activating programmatically, 100, 101adding to labels, 116

animating, 135-139clearing, 15, 63collection view, 334creating explicit constraints, 103, 104creating in Interface Builder, 57-64creating programmatically, 98-104implicit, 188nearest neighbor and, 58overview, 57pin, 59, 60resolving unsatisfiable, 107specifying, 13

constraintWithItem:attribute:relatedBy……:toItem:attribute:multiplier:constant:,103, 104content compression, 190contentMode (UIImageView), 222, 223contentView (UITableViewCell), 154control events, 289controller objects, 5controls, programmatic, 104Core Data

vs. archiving, 353attributes, 354fetch requests, 364persistent store formats, 359relationship management with, 369-384role of, 354subclassing NSManagedObject, 356-358transforming values, 356

Core Graphics, 93count (arrays), 34currentLocale, 110

Ddata source methods, 152, 174, 335, 364data storage

(see also archiving, Core Data)for application data, 246, 247binary, 255, 261with NSData, 254

dataSource (UITableView), 145, 149-153debugging

(see also debugging tools, exceptions)debugging tools

issue navigator, 23Xcode, 35

Page 44: iOS Programming: The Big Nerd Ranch Guideptgmedia.pearsoncmg.com/images/9780134390734/samplepages/...iii Acknowledgments While our names appear on the cover, many people helped make

Index

389

declarationsprotocol, 76

default: (switch statement), 39delegation

design pattern, 174for UIImagePickerController, 228for UITableView, 145overview, 76-78UICollectionViewDelegate, 345

deleteRowsAtIndexPaths(_:withRowAnimati……on:), 168dependency injection, 151dependency inversion principle, 151design patterns, 174DetailViewController, 236, 265-271developer documentation, 244devices

checking for camera, 227-229display resolution, 47Retina display, 24, 93, 94

dictionaries(see also JSON data)about, 31, 32accessing, 36subscripting, 36using, 233, 234writing to filesystem, 261

directoriesapplication, 246, 247Documents, 246Library/Caches, 246Library/Preferences, 246lproj, 113, 127temporary, 246

display resolution, 47document outline (Interface Builder), 7documentation

developer, 244opening, 129for Swift, 40

Documents directory, 246Double, 31drawing (see views)drill-down interface, 203Dynamic Type, 181-184

EeditButtonItem, 219editing (UITableView,UITableViewController), 161, 165editor area (Xcode), 7encodeInteger(_:forKey:), 242encodeObject(_:forKey:), 242encodeWithCoder(_:), 248encodeWithCoder:, 242-244endEditing(_:), 214entities

creating, 361defined, 354modeling, 354-356relationships between, 370-372saving changes to, 363

enumerate(), 37enums (enumerations)

defined, 39overview of, 320and raw values, 40and switch statements, 39

error handling, 257-259, 346errors

dealing with, 35in playgrounds, 30traps, 32

event handling, 212events

control, 104, 289touch, 212, 274

(see also touch events)exceptions

vs. error handling, 261internal inconsistency, 166Swift vs. other languages, 261

expressions, string interpolation and, 37extensions, 347

Ffallthrough (switch statement), 39fetch requests, 364file inspector, 121file URLs, retrieving, 247filesystem, writing to, 254-256, 261first responder

becoming, 72

Page 45: iOS Programming: The Big Nerd Ranch Guideptgmedia.pearsoncmg.com/images/9780134390734/samplepages/...iii Acknowledgments While our names appear on the cover, many people helped make

Index

390

and nil-targeted actions, 289overview, 211-215resigning, 72, 213, 214and responder chain, 288and UIMenuController, 297

Flickr, 308Float, 31floating-point types, 31, 33fonts

changing preferred size, 183customizing size, 54

for-in, 37forced unwrapping (of optionals), 35frame (UIView), 45-47frameworks

Core Data (see Core Data)definition of, 46linking manually, 84

functions(see also individual function names)callback, 76

Ggenstrings, 125gesture recognizer (see UIGestureRecognizer)gestures

(see also UIGestureRecognizer,UIScrollView)discrete vs. continuous, 299long press, 299, 300panning, 299-303taps, 292-298

GUIDs, 233

HHashable, 31header view (UITableView), 161-164hierarchies, view, 42-51Homepwner application

adding an image store, 231adding drill-down interface, 204-220adding item images, 221-237adjusting view properties per size class, 267application sandbox, 250creating nested stack views, 186-193enabling editing, 161-170object diagrams, 149, 206

storing images, 254-259horizontal ambiguity, 60HTTP protocol, 331, 332

IIBAction, 18, 226@IBInspectable, 286IBOutlet, 16, 196-198icons

(see also images)application, 24, 25asset catalogs for, 24camera, 224

if-let, 36image picker (see UIImagePickerController)imageNamed:, 94imagePickerController:didFinishPickingM……ediaWithInfo:, 228imagePickerControllerDidCancel:, 228images

(see also camera, icons, UIImageView)accessing from the cache, 234caching, 254-259displaying in UIImageView, 222, 223downloading image data, 327, 345-347fetching, 232modeling Photo class, 317navigating to photos, 350-352for Retina display, 93saving, 230saving to disk, 367storing, 231-233wrapping in NSData, 254

imageWithContentsOfFile(_:), 255implementation files, navigating, 238implicit constraints, 188inactive state, 252inequality constraints, 118init(coder:), 245init(frame:), 45init?(contentsOfFile:encoding:error:), 261initial view controller, 82initializers

about, 33convenience, 147custom, 147, 148designated, 147

Page 46: iOS Programming: The Big Nerd Ranch Guideptgmedia.pearsoncmg.com/images/9780134390734/samplepages/...iii Acknowledgments While our names appear on the cover, many people helped make

Index

391

free, 148member-wise, 277for standard types, 33

initWithCoder:, 242inspectors (Xcode)

connections, 20file, 121

instance variables, 248(see also pointers, properties)

instances, 33Int, 31integer types, 31Interface Builder

(see also Xcode)adding constraints in, 59attributes inspector, 51canvas, 7connecting objects, 16-20connecting with source files, 178document outline, 7modifying view attributes, 286and properties, 178scene, 8setting outlets in, 17, 196, 197setting target-action in, 19size inspector, 52

interface filesbad connections in, 198Base internationalization and, 113connecting with source files, 226making connections in, 226

internal inconsistency exception, 166internationalization, 109-113, 127

(see also localization)intrinsic content size, 60inverse relationships, 371iOS simulator

running applications on, 12sandbox location, 250saving images to, 229viewing application bundle in, 263

iPad(see also devices)application icons for, 24running iPhone applications on, 3

isEmpty (strings), 34isSourceTypeAvailable:, 227issue navigator, 23

JJSON data, 318, 319

Kkey-value pairs

in dictionaries, 31in JSON data, 318in web services, 310

keyboardattributes, 68-71dismissing, 72, 211-215number pad, 220

keyscreating/using, 233in dictionaries, 31

Llabels

adding, 52adding additional, 132adding constraints to, 116adding to tab bar, 88customizing, 53updating preferred text size, 184

language settings, 109(see also localization)

launch images, 26layers (of views), 43layout attributes, 56, 57layout guides, 101, 141lazy loading, 82, 91let, 29libraries

(see also frameworks)object, 9

Library/Caches directory, 246Library/Preferences directory, 246literal values, 32loadView, 82, 97local variables, 37localization

Base internationalization and, 113internationalization, 109-113, 127lproj directories, 113, 127NSBundle, 127strings tables, 124-126user settings for, 109

Page 47: iOS Programming: The Big Nerd Ranch Guideptgmedia.pearsoncmg.com/images/9780134390734/samplepages/...iii Acknowledgments While our names appear on the cover, many people helped make

Index

392

XLIFF data type, 128locationInView:, 296loops

examining in Value History, 38for, 37for-in, 37in Swift, 37

low-memory warnings, 230lproj directories, 113, 127

Mmain bundle, 113, 127

(see also application bundle)main interface, 85main thread, 330mainBundle, 264margins, 102, 103// MARK:, 239, 240member-wise initializers, 277memory management

memory warnings, 230UITableViewCell, 156

menus (UIMenuController), 297, 298, 306messages

(see also methods)action, 289, 292, 298log, 285UIResponder, 275

methods(see also individual method names)action, 18, 289data source, 152defined, 27, 34protocol, 79static, 27

minimumPressDuration, 299modal view controller, 172, 228model layer, 5Model-View-Controller (MVC), 5-7, 145, 174multi-threading, 330multipleTouchEnabled (UIView), 281multitouch, enabling, 281mutableSetValueForKey(_:), 377MVC (Model-View-Controller), 5-7, 145, 174

Nnaming conventions

cell reuse identifiers, 156delegate protocols, 76

navigation controllers (seeUINavigationController)navigationItem (UIViewController), 216navigators (Xcode)

defined, 4issue, 23project, 4

nearest neighbor, 58nextResponder, 288nil-targeted actions, 289NSBundle, 127NSCoder, 242, 245NSCoding protocol, 242-245NSData, 254NSDate, 261NSDateFormatter, 110NSFetchRequest, 364NSIndexPath, 155, 168NSJSONSerialization, 319NSKeyedArchiver, 248-251NSKeyedUnarchiver, 251NSLocale, 110NSLocalizedString(), 124, 126NSManagedObject, 356-358, 372-382NSNumber, 261NSString

conversion to, 243property list serializable, 261

NSTemporaryDirectory, 246NSURL, 312-315NSURLRequest, 314, 315, 331, 332NSURLSession, 314-316NSURLSessionDataTask, 315, 316, 326, 330NSURLSessionTask, 331NSUserDefaults, 246NSUUID, 233, 234NSValueTransformer, 356number formatters, 75, 110-113number pad, 220

Oobject graphs, 353object library, 9objects

(see also memory management)

Page 48: iOS Programming: The Big Nerd Ranch Guideptgmedia.pearsoncmg.com/images/9780134390734/samplepages/...iii Acknowledgments While our names appear on the cover, many people helped make

Index

393

property list serializable, 261optional, 79optional binding, 36optional methods (protocols), 79optionals

about, 34and dictionary subscripting, 36forced unwrapping of, 35if-let, 36and optional binding, 36syntax for, 34unwrapping, 35

outletsautogenerating/connecting, 196connecting constraints to, 136connecting with source files, 178defined, 16setting, 16-18setting in Interface Builder, 195

Ppadding, 158parallel computing, 330parent-child contexts, 382-384Photorama application

adding persistence to, 353-368adding tags to photos, 369-384collection view, 333-344downloading image data, 327-329web service requests, 308-326

photos (see camera, images)pixels, 47playgrounds (Xcode), 28-30

errors in, 30Value History, 38viewing console in, 35

pointersin Interface Builder (see outlets)

points (vs. pixels), 47predicates, 364preferences, 246

(see also Dynamic Type, localization)prepareForSegue:sender:, 200presentViewController:animated:completion:,228preview assistant, 114project navigator, 4

projectscleaning and building, 123creating, 2-4target settings in, 263

propertiescreating in Interface Builder, 178defined, 34

property list serializable objects, 261property observer, 74protocol, 76protocols

conforming to, 76declaring, 76delegate, 76-78NSCoding, 242-245optional methods in, 79required methods in, 79structure of, 76UIApplicationDelegate, 254UICollectionViewDataSource protocol, 335UICollectionViewDelegate, 345UIGestureRecognizerDelegate, 301, 302UIImagePickerControllerDelegate, 228,230UINavigationControllerDelegate, 230UIResponderStandardEditActions, 306UITableViewDataSource, 145, 152, 153, 155,168, 169UITableViewDelegate, 145UITextFieldDelegate, 76, 211

pseudolanguage, 115

QQuartz, 93 (see Core Graphics)query items, 310Quick Help, 244Quick Help (Xcode), 30Quiz application, 2-26

RRange, 37rawValue (enums), 40reference pages, 244reference types, 277region settings, 109reordering controls, 170required methods (protocols), 79

Page 49: iOS Programming: The Big Nerd Ranch Guideptgmedia.pearsoncmg.com/images/9780134390734/samplepages/...iii Acknowledgments While our names appear on the cover, many people helped make

Index

394

requireGestureRecognizerToFail(_:), 304resignFirstResponder, 72, 213resources

asset catalogs for, 24defined, 24, 263

responder chain, 288responders (see first responder, UIResponder)Retina display, 24, 93, 94reuse identifiers, 335reuseIdentifier (UITableViewCell), 156reverse(), 34root view controller (UINavigationController),205-207rows (UITableView)

adding, 166, 167deleting, 168moving, 169, 170

Ssandbox, application, 245-247, 263schemes, 12sections (UITableView), 153, 161segues, 194sendAction(_:to:from:forEvent:), 289sendActionsForControlEvents(_:), 289setEditing:animated:, 165, 219sets, 32, 33settings (see preferences)Settings application, 246simulator

running applications on, 12sandbox location, 250saving images to, 229viewing application bundle in, 263

size classes, 265-271sort descriptors (NSFetchRequest), 364sourceType (UIImagePickerController), 226,227stack views, 185-193states, application, 252-254static methods, 27String

internationalizing, 124writing to filesystem, 255-261

string interpolation, 37strings

(see also NSString)

initializers for, 33interpolation, 37isEmpty, 34literal, 32

strings tables, 124-126structs, 277subscripting

arrays, 32dictionaries, 36

subviews, 42, 92superview, 48suspended state, 252, 254Swift

about, 27documentation for, 40enumerations and switch statement, 39extensions in, 347loops and string interpolation, 37optional types in, 34, 257-259types in, 27using standard types, 28-34value types, 277

switch, 39switch statements, 39

Ttab bar controllers (see UITabBarController)tab bar items, 88-90table view cells (see UITableViewCell)table view controllers (seeUITableViewController)table views (see UITableView)tables (database), 353tableView, 159tableView(_:commitEditingStyle:forRowAt……IndexPath:), 168tableView(_:moveRowAtIndexPath:toIndexP……ath:), 169tableView:cellForRowAtIndexPath:, 152,155-157tableView:numberOfRowsInSection:, 152, 153tags

adding to photos, 377-381adding to the interface, 372-377creating relationships between, 370-372

target-action pairsdefined, 18, 19, 174

Page 50: iOS Programming: The Big Nerd Ranch Guideptgmedia.pearsoncmg.com/images/9780134390734/samplepages/...iii Acknowledgments While our names appear on the cover, many people helped make

Index

395

setting programmatically, 218and UIControl, 289and UIGestureRecognizer, 292

targets, build settings for, 263templates (Xcode), xvtext

(see also Auto Layout)aligning, 67compression of, 190customizing appearance, 53, 67dynamic styling of, 181input, 65-73

textFieldShouldReturn:, 211threads, 330timing functions, 139, 140tmp directory, 246to-many relationships, 370to-one relationships, 370toggleEditingMode:, 165toolbars

adding, 224adding buttons to, 225adding constraints to, 224anchoring, 372

topViewController (UINavigationController),205touch events

basics of, 274, 275defined, 212enabling multitouch, 281-285and responder chain, 288and target-action pairs, 289and UIControl, 289

touchesBegan(_:withEvent:), 274touchesCancelled(_:withEvent:), 274touchesEnded(_:withEvent:), 274touchesMoved(_:withEvent:), 274TouchTracker application

creating, 275drawing lines, 276-285recognizing gestures, 291-306

transformable attributes (Core Data), 356translationInView(_:), 302traps, 32tuples, 37type inference, 30types

boolean, 31

floating-point, 31, 33hashable, 31inference of, 30instances of, 33integer, 31sets, 32, 33specifying, 30tuples, 37

UUI thread, 330UIAlertController, 170-173UIApplication

and events, 274and responder chain, 288, 289

UIApplicationDelegate, 254UIBarButtonItem, 217-219, 224-226UICollectionViewCell, 341-344UICollectionViewDataSource protocol, 335UICollectionViewDelegate protocol, 345UICollectionViewFlowLayout, 333-340UIColor, 46UIControl, 289UIControlEvent.TouchUpInside, 289UIControlEvents, 104UIGestureRecognizer

action messages of, 292, 299cancelsTouchesInView, 300chaining recognizers, 304delaying touches, 304described, 291detecting taps, 292-298enabling simultaneous recognizers, 301implementing multiple, 294-296, 301-303intercepting touches from view, 292, 300, 301locationInView:, 296long press, 299, 300panning, 299-303state (property), 299, 302, 304subclasses, 72, 292, 304subclassing, 305translationInView(_:), 302and UIResponder methods, 300

UIGestureRecognizerDelegate, 301, 302UIImage, 255

(see also images, UIImageView)UIImageJPEGRepresentation, 255

Page 51: iOS Programming: The Big Nerd Ranch Guideptgmedia.pearsoncmg.com/images/9780134390734/samplepages/...iii Acknowledgments While our names appear on the cover, many people helped make

Index

396

UIImagePickerControllerinstantiating, 226-228presenting, 228-230

UIImagePickerControllerDelegate, 228, 230UIImageView, 222, 223UIInterpolatingMotionEffect, 130UIKit, 46UILongPressGestureRecognizer, 299, 300UIMenuController, 297, 298, 306UINavigationBar, 206-220UINavigationController

(see also view controllers)adding view controllers to, 210described, 205-208instantiating, 207managing view controller stack, 205root view controller, 205, 206in storyboards, 194topViewController, 205, 206and UINavigationBar, 216-219view, 206viewControllers, 205viewWillAppear:, 210viewWillDisappear:, 210

UINavigationControllerDelegate, 230UINavigationItem, 216-219UIPanGestureRecognizer, 299-303UIResponder

menu actions, 306and responder chain, 288and touch events, 274

UIResponderStandardEditActions (protocol),306UIScrollView, 158UIStackView, 187-193UIStoryboardSegue, 194-200UITabBarController

implementing, 85-90vs. UINavigationController, 203view, 87

UITabBarItem, 88-90UITableView, 143-145

(see also UITableViewCell,UITableViewController)adding rows to, 166, 167deleting rows from, 168editing mode of, 161, 165, 176, 219editing property, 161, 165

footer view, 161header view, 161-164moving rows in, 169, 170populating, 149-156sections, 153, 161view, 146

UITableViewCellcell styles, 154contentView, 154editing styles, 168retrieving instances of, 155, 156reusing instances of, 156-158subclassing, 175-184UITableViewCellStyle, 154

UITableViewCellEditingStyleDelete, 168UITableViewController

(see also UITableView)adding rows, 166, 167data source methods, 152dataSource, 149-153deleting rows, 168described, 145editing property, 165moving rows, 169, 170returning cells, 155, 156subclassing, 146tableView, 159

UITableViewDataSource (protocol), 145, 152,153, 155, 168, 169UITableViewDelegate, 145UITapGestureRecognizer, 72, 292-298UITextField

as first responder, 211, 289and keyboard, 211setting attributes of, 220text editing, 65

UITextFieldDelegate, 76, 211UIToolbar, 217, 225UITouch, 274, 275, 280-285UIView

(see also UIViewController, views)animation documentation, 129defined, 41frame, 45-47instantiating, 45superview, 48

UIViewController(see also UIView, view controllers)

Page 52: iOS Programming: The Big Nerd Ranch Guideptgmedia.pearsoncmg.com/images/9780134390734/samplepages/...iii Acknowledgments While our names appear on the cover, many people helped make

Index

397

loadView, 82, 97navigationItem, 216tabBarItem, 88view, 82, 288viewDidLoad, 92viewWillAppear:, 92, 230

UIWindowpurpose of, 42and responder chain, 288

unarchiveObjectWithFile(_:), 251URLForResource(_:withExtension:), 127URLs, 309

(see also NSURL)user alerts, displaying, 170-173user interface

(see also Auto Layout, views)drill-down, 203keyboard, 211

user settings (see preferences)UUIDs, 233, 356

Vvalue types, 277var, 29variables, 29

(see also instance variables, local variables,pointers, properties)

view (UIViewController), 82view controllers

(see also UIViewController, views)allowing access to image store, 232interacting with, 92lazy loading of views, 82, 91modal, 172, 228navigating between, 194presenting, 85reloading subviews, 230root, 205setting initial, 82and view hierarchy, 82, 97

view hierarchy, 42-51, 97viewControllers (UINavigationController),205viewDidLoad, 46, 92views

(see also Auto Layout, touch events, UIView,view controllers)

adding to window, 42, 97animating, 129-139appearing/disappearing, 210content compression resistance priorities, 190content hugging priorities, 189creating programmatically, 97defined, 41drawing to screen, 43in hierarchy, 42, 43layers and, 43lazy loading of, 82, 91misplaced, 62modal presentation of, 228in Model-View-Controller, 5removing from storyboard, 95rendering, 43resizing, 222, 223scroll, 334size and position of, 45-47stack view, 185-193, 267and subviews, 42-51

viewWillAppear:, 92, 210, 230viewWillDisappear:, 210

Wweb services

and HTTP protocol, 331, 332with JSON data, 318, 319and NSURLSession, 314-316overview, 307, 308requesting data from, 309-316

wildcard Any Width/Height layout, 266workspaces (Xcode), 4WorldTrotter application

adding tab bar controller, 85-90configuring, 44implementing temperature conversion, 73interface layout, 51localizing, 110-127multiple view controllers for, 81programmatic views in, 95text input, 65-73

writeToURL(_:atomically:), 255writeToURL(_:atomically:encoding:error:),261

Page 53: iOS Programming: The Big Nerd Ranch Guideptgmedia.pearsoncmg.com/images/9780134390734/samplepages/...iii Acknowledgments While our names appear on the cover, many people helped make

Index

398

X.xcassets (asset catalog), 24.xcdatamodeld (data model file), 354Xcode

(see also debugging tools, Interface Builder,projects, iOS simulator)API Reference, 244asset catalogs, 24assistant editor, 226creating projects in, 2-4documentation, 129editor area, 7file inspector, 121issue navigator, 23navigator area, 4navigators, 4object library, 9organizing methods with // MARK:, 239playgrounds, 28-30Quick Help, 30, 244schemes, 12source editor jump bar, 238versions, 2workspaces, 4

XLIFF data type, 128XML property lists, 261