
- •Contents at a Glance
- •About the Authors
- •About the Technical Reviewer
- •Acknowledgments
- •Preface
- •What This Book Is
- •What You Need
- •Developer Options
- •What You Need to Know
- •What’s Different About Coding for iOS?
- •Only One Active Application
- •Only One Window
- •Limited Access
- •Limited Response Time
- •Limited Screen Size
- •Limited System Resources
- •No Garbage Collection, but…
- •Some New Stuff
- •A Different Approach
- •What’s in This Book
- •What’s New in This Update?
- •Are You Ready?
- •Setting Up Your Project in Xcode
- •The Xcode Workspace Window
- •The Toolbar
- •The Navigator View
- •The Jump Bar
- •The Utility Pane
- •Interface Builder
- •New Compiler and Debugger
- •A Closer Look at Our Project
- •Introducing Xcode’s Interface Builder
- •What’s in the Nib File?
- •The Library
- •Adding a Label to the View
- •Changing Attributes
- •Some iPhone Polish—Finishing Touches
- •Bring It on Home
- •The Model-View-Controller Paradigm
- •Creating Our Project
- •Looking at the View Controller
- •Understanding Outlets and Actions
- •Outlets
- •Actions
- •Cleaning Up the View Controller
- •Designing the User Interface
- •Adding the Buttons and Action Method
- •Adding the Label and Outlet
- •Writing the Action Method
- •Trying It Out
- •Looking at the Application Delegate
- •Bring It on Home
- •A Screen Full of Controls
- •Active, Static, and Passive Controls
- •Creating the Application
- •Implementing the Image View and Text Fields
- •Adding the Image View
- •Resizing the Image View
- •Setting View Attributes
- •The Mode Attribute
- •Interaction Checkboxes
- •The Alpha Value
- •Background
- •Drawing Checkboxes
- •Stretching
- •Adding the Text Fields
- •Text Field Inspector Settings
- •Setting the Attributes for the Second Text Field
- •Creating and Connecting Outlets
- •Closing the Keyboard
- •Closing the Keyboard When Done Is Tapped
- •Touching the Background to Close the Keyboard
- •Adding the Slider and Label
- •Creating and Connecting the Actions and Outlets
- •Implementing the Action Method
- •Adding Two Labeled Switches
- •Connecting and Creating Outlets and Actions
- •Implementing the Switch Actions
- •Adding the Button
- •Connecting and Creating the Button Outlets and Actions
- •Implementing the Segmented Control Action
- •Implementing the Action Sheet and Alert
- •Conforming to the Action Sheet Delegate Method
- •Showing the Action Sheet
- •Spiffing Up the Button
- •Using the viewDidLoad Method
- •Control States
- •Stretchable Images
- •Crossing the Finish Line
- •The Mechanics of Autorotation
- •Points, Pixels, and the Retina Display
- •Autorotation Approaches
- •Handling Rotation Using Autosize Attributes
- •Configuring Supported Orientations
- •Specifying Rotation Support
- •Designing an Interface with Autosize Attributes
- •Using the Size Inspector’s Autosize Attributes
- •Setting the Buttons’ Autosize Attributes
- •Restructuring a View When Rotated
- •Creating and Connecting Outlets
- •Moving the Buttons on Rotation
- •Swapping Views
- •Designing the Two Views
- •Implementing the Swap
- •Changing Outlet Collections
- •Rotating Out of Here
- •Common Types of Multiview Apps
- •The Architecture of a Multiview Application
- •The Root Controller
- •Anatomy of a Content View
- •Building View Switcher
- •Creating Our View Controller and Nib Files
- •Modifying the App Delegate
- •Modifying BIDSwitchViewController.h
- •Adding a View Controller
- •Building a View with a Toolbar
- •Writing the Root View Controller
- •Implementing the Content Views
- •Animating the Transition
- •Switching Off
- •The Pickers Application
- •Delegates and Data Sources
- •Setting Up the Tab Bar Framework
- •Creating the Files
- •Adding the Root View Controller
- •Creating TabBarController.xib
- •The Initial Test Run
- •Implementing the Date Picker
- •Implementing the Single-Component Picker
- •Declaring Outlets and Actions
- •Building the View
- •Implementing the Controller As a Data Source and Delegate
- •Implementing a Multicomponent Picker
- •Declaring Outlets and Actions
- •Building the View
- •Implementing the Controller
- •Implementing Dependent Components
- •Creating a Simple Game with a Custom Picker
- •Writing the Controller Header File
- •Building the View
- •Adding Image Resources
- •Implementing the Controller
- •The spin Method
- •The viewDidLoad Method
- •Final Details
- •Linking in the Audio Toolbox Framework
- •Final Spin
- •Table View Basics
- •Table Views and Table View Cells
- •Grouped and Plain Tables
- •Implementing a Simple Table
- •Designing the View
- •Writing the Controller
- •Adding an Image
- •Using Table View Cell Styles
- •Setting the Indent Level
- •Handling Row Selection
- •Changing the Font Size and Row Height
- •Customizing Table View Cells
- •Adding Subviews to the Table View Cell
- •Creating a UITableViewCell Subclass
- •Adding New Cells
- •Implementing the Controller’s Code
- •Loading a UITableViewCell from a Nib
- •Designing the Table View Cell in Interface Builder
- •Using the New Table View Cell
- •Grouped and Indexed Sections
- •Building the View
- •Importing the Data
- •Implementing the Controller
- •Adding an Index
- •Implementing a Search Bar
- •Rethinking the Design
- •A Deep Mutable Copy
- •Updating the Controller Header File
- •Modifying the View
- •Modifying the Controller Implementation
- •Copying Data from allNames
- •Implementing the Search
- •Changes to viewDidLoad
- •Changes to Data Source Methods
- •Adding a Table View Delegate Method
- •Adding Search Bar Delegate Methods
- •Adding a Magnifying Glass to the Index
- •Adding the Special Value to the Keys Array
- •Suppressing the Section Header
- •Telling the Table View What to Do
- •Putting It All on the Table
- •Navigation Controller Basics
- •Stacky Goodness
- •A Stack of Controllers
- •Nav, a Hierarchical Application in Six Parts
- •Meet the Subcontrollers
- •The Disclosure Button View
- •The Checklist View
- •The Rows Control View
- •The Movable Rows View
- •The Deletable Rows View
- •The Editable Detail View
- •The Nav Application’s Skeleton
- •Creating the Top-Level View Controller
- •Setting Up the Navigation Controller
- •Adding the Images to the Project
- •First Subcontroller: The Disclosure Button View
- •Creating the Detail View
- •Modifying the Disclosure Button Controller
- •Adding a Disclosure Button Controller Instance
- •Second Subcontroller: The Checklist
- •Creating the Checklist View
- •Adding a Checklist Controller Instance
- •Third Subcontroller: Controls on Table Rows
- •Creating the Row Controls View
- •Adding a Rows Control Controller Instance
- •Fourth Subcontroller: Movable Rows
- •Creating the Movable Row View
- •Adding a Move Me Controller Instance
- •Fifth Subcontroller: Deletable Rows
- •Creating the Deletable Rows View
- •Adding a Delete Me Controller Instance
- •Sixth Subcontroller: An Editable Detail Pane
- •Creating the Data Model Object
- •Creating the Detail View List Controller
- •Creating the Detail View Controller
- •Adding an Editable Detail View Controller Instance
- •But There’s One More Thing. . .
- •Breaking the Tape
- •Creating a Simple Storyboard
- •Dynamic Prototype Cells
- •Dynamic Table Content, Storyboard-Style
- •Editing Prototype Cells
- •Good Old Table View Data Source
- •Will It Load?
- •Static Cells
- •Going Static
- •So Long, Good Old Table View Data Source
- •You Say Segue, I Say Segue
- •Creating Segue Navigator
- •Filling the Blank Slate
- •First Transition
- •A Slightly More Useful Task List
- •Viewing Task Details
- •Make More Segues, Please
- •Passing a Task from the List
- •Handling Task Details
- •Passing Back Details
- •Making the List Receive the Details
- •If Only We Could End with a Smooth Transition
- •Split Views and Popovers
- •Creating a SplitView Project
- •The Storyboard Defines the Structure
- •The Code Defines the Functionality
- •The App Delegate
- •The Master View Controller
- •The Detail View Controller
- •Here Come the Presidents
- •Creating Your Own Popover
- •iPad Wrap-Up
- •Getting to Know Your Settings Bundle
- •The AppSettings Application
- •Creating the Project
- •Working with the Settings Bundle
- •Adding a Settings Bundle to Our Project
- •Setting Up the Property List
- •Adding a Text Field Setting
- •Adding an Application Icon
- •Adding a Secure Text Field Setting
- •Adding a Multivalue Field
- •Adding a Toggle Switch Setting
- •Adding the Slider Setting
- •Adding Icons to the Settings Bundle
- •Adding a Child Settings View
- •Reading Settings in Our Application
- •Retrieving User Settings
- •Creating the Main View
- •Updating the Main View Controller
- •Registering Default Values
- •Changing Defaults from Our Application
- •Keeping It Real
- •Beam Me Up, Scotty
- •Your Application’s Sandbox
- •Getting the Documents Directory
- •Getting the tmp Directory
- •File-Saving Strategies
- •Single-File Persistence
- •Multiple-File Persistence
- •Using Property Lists
- •Property List Serialization
- •The First Version of the Persistence Application
- •Creating the Persistence Project
- •Designing the Persistence Application View
- •Editing the Persistence Classes
- •Archiving Model Objects
- •Conforming to NSCoding
- •Implementing NSCopying
- •Archiving and Unarchiving Data Objects
- •The Archiving Application
- •Implementing the BIDFourLines Class
- •Implementing the BIDViewController Class
- •Using iOS’s Embedded SQLite3
- •Creating or Opening the Database
- •Using Bind Variables
- •The SQLite3 Application
- •Linking to the SQLite3 Library
- •Modifying the Persistence View Controller
- •Using Core Data
- •Entities and Managed Objects
- •Key-Value Coding
- •Putting It All in Context
- •Creating New Managed Objects
- •Retrieving Managed Objects
- •The Core Data Application
- •Designing the Data Model
- •Creating the Persistence View and Controller
- •Persistence Rewarded
- •Managing Document Storage with UIDocument
- •Building TinyPix
- •Creating BIDTinyPixDocument
- •Code Master
- •Initial Storyboarding
- •Creating BIDTinyPixView
- •Storyboard Detailing
- •Adding iCloud Support
- •Creating a Provisioning Profile
- •Enabling iCloud Entitlements
- •How to Query
- •Save Where?
- •Storing Preferences on iCloud
- •What We Didn’t Cover
- •Grand Central Dispatch
- •Introducing SlowWorker
- •Threading Basics
- •Units of Work
- •GCD: Low-Level Queueing
- •Becoming a Blockhead
- •Improving SlowWorker
- •Don’t Forget That Main Thread
- •Giving Some Feedback
- •Concurrent Blocks
- •Background Processing
- •Application Life Cycle
- •State-Change Notifications
- •Creating State Lab
- •Exploring Execution States
- •Making Use of Execution State Changes
- •Handling the Inactive State
- •Handling the Background State
- •Removing Resources When Entering the Background
- •Saving State When Entering the Background
- •A Brief Journey to Yesteryear
- •Back to the Background
- •Requesting More Backgrounding Time
- •Grand Central Dispatch, Over and Out
- •Two Views of a Graphical World
- •The Quartz 2D Approach to Drawing
- •Quartz 2D’s Graphics Contexts
- •The Coordinate System
- •Specifying Colors
- •A Bit of Color Theory for Your iOS Device’s Display
- •Other Color Models
- •Color Convenience Methods
- •Drawing Images in Context
- •Drawing Shapes: Polygons, Lines, and Curves
- •The QuartzFun Application
- •Setting Up the QuartzFun Application
- •Creating a Random Color
- •Defining Application Constants
- •Implementing the QuartzFunView Skeleton
- •Creating and Connecting Outlets and Actions
- •Implementing the Action Methods
- •Adding Quartz 2D Drawing Code
- •Drawing the Line
- •Drawing the Rectangle and Ellipse
- •Drawing the Image
- •Optimizing the QuartzFun Application
- •The GLFun Application
- •Setting Up the GLFun Application
- •Creating BIDGLFunView
- •Updating BIDViewController
- •Updating the Nib
- •Finishing GLFun
- •Drawing to a Close
- •Multitouch Terminology
- •The Responder Chain
- •Responding to Events
- •Forwarding an Event: Keeping the Responder Chain Alive
- •The Multitouch Architecture
- •The Four Touch Notification Methods
- •The TouchExplorer Application
- •The Swipes Application
- •Automatic Gesture Recognition
- •Implementing Multiple Swipes
- •Detecting Multiple Taps
- •Detecting Pinches
- •Defining Custom Gestures
- •The CheckPlease Application
- •The CheckPlease Touch Methods
- •Garçon? Check, Please!
- •The Location Manager
- •Setting the Desired Accuracy
- •Setting the Distance Filter
- •Starting the Location Manager
- •Using the Location Manager Wisely
- •The Location Manager Delegate
- •Getting Location Updates
- •Getting Latitude and Longitude Using CLLocation
- •Error Notifications
- •Trying Out Core Location
- •Updating Location Manager
- •Determining Distance Traveled
- •Wherever You Go, There You Are
- •Accelerometer Physics
- •Don’t Forget Rotation
- •Core Motion and the Motion Manager
- •Event-Based Motion
- •Proactive Motion Access
- •Accelerometer Results
- •Detecting Shakes
- •Baked-In Shaking
- •Shake and Break
- •Accelerometer As Directional Controller
- •Rolling Marbles
- •Writing the Ball View
- •Calculating Ball Movement
- •Rolling On
- •Using the Image Picker and UIImagePickerController
- •Implementing the Image Picker Controller Delegate
- •Road Testing the Camera and Library
- •Designing the Interface
- •Implementing the Camera View Controller
- •It’s a Snap!
- •Localization Architecture
- •Strings Files
- •What’s in a Strings File?
- •The Localized String Macro
- •Real-World iOS: Localizing Your Application
- •Setting Up LocalizeMe
- •Trying Out LocalizeMe
- •Localizing the Nib
- •Localizing an Image
- •Generating and Localizing a Strings File
- •Localizing the App Display Name
- •Auf Wiedersehen
- •Apple’s Documentation
- •Mailing Lists
- •Discussion Forums
- •Web Sites
- •Blogs
- •Conferences
- •Follow the Authors
- •Farewell
- •Index

CHAPTER 4: More User Interface Fun |
79 |
Setting View Attributes
Select your image view, and then switch your attention back over to the attributes inspector. Below the Image View section of the inspector is the View section. As you may have deduced, the pattern here is that the attributes that are specific to the selected object are shown at the top, followed by more general attributes that apply to the selected object’s parent class. In this case, the parent class of UIImageView is UIView, so the next section is simply labeled View, and it contains attributes that any view class will have.
The Mode Attribute
The first option in the view inspector is a popup menu labeled Mode. The Mode menu defines how the view will display its content. This determines how the image will be aligned inside the view and whether it will be scaled to fit. Feel free to play with the various options, but the default value of Scale To Fill will work fine for now.
Keep in mind that choosing any option that causes the image to scale will potentially add processing overhead, so it’s best to avoid those and size your images correctly before you import them. If you want to display the same image at multiple sizes, generally it’s better to have multiple copies of the image at different sizes in your project, rather than force your iOS device to do scaling at runtime. Of course, there are times when scaling at runtime is appropriate; this is a guideline, not a rule.
Tag
The next item, Tag, is worth mentioning, though we won’t be using it in this chapter. All subclasses of UIView, including all views and controls, have a property called tag, which is just a numeric value that you can set here or in code. The tag is designed for your use; the system will never set or change its value. If you assign a tag value to a control or view, you can be sure that the tag will always have that value unless you change it.
Tags provide an easy, language-independent way of identifying objects on your interface. Let’s say you have five different buttons, each with a different label, and you want to use a single action method to handle all five buttons. In that case, you probably need some way to differentiate among the buttons when your action method is called. Sure, you could look at the button’s title, but code that does that probably won’t work when your application is translated into Swahili or Sanskrit. Unlike labels, tags will never change, so if you set a tag value here in Interface Builder, you can then use that as a fast and reliable way to check which control was passed into an action method in the sender argument.
www.it-ebooks.info

80 |
CHAPTER 4: More User Interface Fun |
Interaction Checkboxes
The two checkboxes in the Interaction section have to do with user interaction. The first checkbox, User Interaction Enabled, specifies whether the user can do anything at all with this object. For most controls, this box will be checked, because if it’s not, the control will never be able to trigger action methods. However, image views default to unchecked because they are often used just for the display of static information. Since all we’re doing here is displaying a picture on the screen, there is no need to turn this on.
The second checkbox is Multiple Touch, and it determines whether this control is capable of receiving multitouch events. Multitouch events allow complex gestures like the pinch gesture used to zoom in in many iOS applications. We’ll talk more about gestures and multitouch events in Chapter 13. Since this image view doesn’t accept user interaction at all, there’s no reason to turn on multitouch events, so leave the checkbox unchecked.
The Alpha Value
The next item in the inspector is Alpha. Be careful with this one. Alpha defines how transparent your image is—how much of what’s beneath it shows through. It’s defined as a floating-point number between 0.0 and 1.0, where 0.0 is fully transparent and 1.0 is completely opaque. If you have any value less than 1.0, your iOS device will draw this view with some amount of transparency so that any objects underneath it show through. With a value of less than 1.0, even if there’s nothing actually underneath your image, you will cause your application to spend processor cycles calculating transparency, so don’t set Alpha to anything other than 1.0 unless you have a very good reason for doing so.
Background
The next item down, Background, is a property inherited from UIView, and determines the color of the background for the view. For image views, this matters only when an image doesn’t fill its view and is letterboxed or when parts of the image are transparent. Since we’ve sized our view to perfectly match our image, this setting will have no visible effect, so we can leave it alone.
Drawing Checkboxes
Below Background are a series of Drawing checkboxes. The first one is labeled Opaque. That should be checked by default; if not, click to check that checkbox. This tells iOS that nothing behind your view needs to be drawn and allows iOS’s drawing methods to do some optimizations that speed up drawing.
You might be wondering why we need to select the Opaque checkbox when we’ve already set the value of Alpha to 1.0 to indicate no transparency. The alpha value applies to the parts of the image to be drawn, but if an image doesn’t completely fill the image view, or there are holes in the image thanks to an alpha channel, the objects below will
www.it-ebooks.info

CHAPTER 4: More User Interface Fun |
81 |
still show through, regardless of the value set in Alpha. By selecting Opaque, we are telling iOS that nothing below this view ever needs to be drawn no matter what, so it does not need to waste processing time with anything below our object. We can safely select the Opaque checkbox, because we earlier selected Size To Fit, which caused the image view to match the size of the image it contains.
The Hidden checkbox does exactly what you think it does. If it’s checked, the user can’t see this object. Hiding an object can be useful at times, as you’ll see later in this chapter when we hide our switches and button, but the vast majority of the time—including now—you want this to remain unchecked.
The next checkbox, Clears Graphics Context, will rarely need to be checked. When it is checked, iOS will draw the entire area covered by the object in transparent black before it actually draws the object. Again, it should be turned off for the sake of performance and because it’s rarely needed. Make sure this checkbox is unchecked (it is likely checked by default).
Clip Subviews is an interesting option. If your view contains subviews, and those subviews are not completely contained within the bounds of its parent view, this checkbox determines how the subviews will be drawn. If Clip Subviews is checked, only the portions of subviews that lie within the bounds of the parent will be drawn. If Clip Subviews is unchecked, subviews will be drawn completely, even if they lie outside the bounds of the parent.
It might seem that the default behavior should be the opposite of what it actually is— Clip Subviews should be unchecked by default. Calculating the clipping area and displaying only part of the subviews is a somewhat costly operation, mathematically speaking, and most of the time, a subview won’t lay outside the bounds of its superview. You can turn on Clip Subviews if you really need it for some reason, but it is off by default for the sake of performance.
The last checkbox in this section, Autoresize Subviews, tells iOS to resize any subviews if this view is resized. Leave this checked (since we don’t allow our view to be resized, it really does not matter whether it’s checked or not).
Stretching
Next up is a section simply labeled Stretching. You can leave your yoga mat in the closet though, because the only stretching going on here is in the form of rectangular views being redrawn as they're resized on the screen. The idea is that rather than the entire content of a view being stretched uniformly, you can keep the outer edges of a view, such as the bezeled edge of a button, looking the same even as the center portion stretches.
The four floating-point values set here let you declare which portion of the rectangle is stretchable by specifying a point at the upper-left corner of the view and the size of the stretchable area, all in the form of a number between 0.0 and 1.0, representing a portion of the overall view size. For example, if you wanted to keep 10% of each edge not stretchy, you would specify 0.1 for both X and Y, and 0.8 for both Width and Height. In
www.it-ebooks.info

82 |
CHAPTER 4: More User Interface Fun |
this case, we're going to leave the default values of 0.0 for X and Y, and 1.0 for Width and Height. Most of the time, you will not change these values.
Adding the Text Fields
With your image view finished, it’s time to bring on the text fields. Grab a text field from the library, and drag it into the View, underneath the image view. Use the blue guidelines to align it with the right margin and snug it just under your image view (see Figure 4–10).
Figure 4–10. We dragged a text field out of the library and dropped it onto the view, just below our image view and touching the right blue guideline.
A horizontal blue guideline will appear just above the text field when you move it very close to the bottom of your image view. That guideline tells you when the object you are dragging is the minimum reasonable distance from an adjacent object. You can leave your text field there for now, but to give it a balanced appearance, consider moving the text field just a little farther down. Remember that you can always edit your nib file again in order to change the position and size of interface elements without needing to change code or reestablish connections.
After you drop the text field, grab a label from the library, and drag that over so it is aligned with the left margin of the view and vertically with the text field you placed earlier. Notice that multiple blue guidelines will pop up as you move the label around, making it easy to align the label to the text field using the top, bottom, or middle of the
www.it-ebooks.info

CHAPTER 4: More User Interface Fun |
83 |
label. We’re going to align the label and the text field using the middle of those guidelines (see Figure 4–11).
Figure 4–11. Aligning the label and text field using the baseline guide
Double-click the label you just dropped, change it to read Name: instead of Label (note the colon character at the end of the label), and press the return key to commit your changes.
Next, drag another text field from the library to the view, and use the guidelines to place it below the first text field (see Figure 4–12).
www.it-ebooks.info

84 |
CHAPTER 4: More User Interface Fun |
Figure 4–12. Adding the second text field
Once you’ve added the second text field, grab another label from the library, and place it on the left side, below the existing label. Again, use the middle blue guideline to align your new label with the second text field. Double-click the new label, and change it to read Number: (don’t forget the colon).
Now, let’s expand the size of the bottom text field to the left, so it snugs up against the right side of the label. Why start with the bottom text field? We want the two text fields to be the same size, and the bottom label is longer.
Single-click the bottom text field, and drag the left resize dot to the left until a blue guideline appears to tell you that you are as close as you should ever be to the label (see Figure 4–13). This particular guideline is somewhat subtle—it’s only as tall as the text field itself, so keep your eyes peeled.
www.it-ebooks.info

CHAPTER 4: More User Interface Fun |
85 |
Figure 4–13. Expanding the size of the bottom text field
Now, expand the top text field in the same way so that it matches the bottom one in size. Once again, a blue guideline provides some help, and this one is easier to spot.
We’re basically finished with the text fields except for one small detail. Look back at Figure 4–5. Do you see how the Name: and Number: are right-aligned? Right now, ours are both against the left margin. To align the right sides of the two labels, click the Name: label, hold down the shift key, and click the Number: label so both labels are selected. Now select Editor Align Right Edges.
When you are finished, the interface should look very much like the one shown in Figure 4–5. The only difference is the light-gray text in each text field. We’ll add that now.
Select the top text field and press 4 to bring up the attributes inspector (see Figure 4–14). The text field is one of the most complex iOS controls, as well as one of the most commonly used. Let’s take a walk through the settings, beginning from the top of the inspector.
www.it-ebooks.info

86 |
CHAPTER 4: More User Interface Fun |
Figure 4–14. The inspector for a text field showing the default values
www.it-ebooks.info