- •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
572 |
CHAPTER 16: Drawing with Quartz and OpenGL |
The QuartzFun Application
Our next application is a simple drawing program (see Figure 16–5). We’re going to build this application twice: now using Quartz, and later using OpenGL ES. This will give you a real feel for the difference between the two environments.
Figure 16–5. Our chapter’s simple drawing application in action
The application features a bar across the top and one across the bottom, each with a segmented control. The control at the top lets you change the drawing color, and the one at the bottom lets you change the shape to be drawn. When you touch and drag, the selected shape will be drawn in the selected color. To minimize the application’s complexity, only one shape will be drawn at a time.
Setting Up the QuartzFun Application
In Xcode, create a new iPhone project using the Single View Application template (with ARC but not using storyboards) and call it QuartzFun. The template has already provided us with an application delegate and a view controller. We’re going to be executing our custom drawing in a custom view, so we need to also create a subclass of UIView where we’ll do the drawing by overriding the drawRect: method.
www.it-ebooks.info
CHAPTER 16: Drawing with Quartz and OpenGL |
573 |
With the QuartzFun folder selected (the folder that currently contains the app delegate and view controller files), press N to bring up the new file assistant, and then select Objective-C class from the Cocoa Touch section. Name the new class
BIDQuartzFunView and make it a subclass of UIView.
We’re going to define some constants, as we’ve done in previous projects, but this time, our constants will be needed by more than one class. We’ll create a header file just for the constants.
Select the QuartzFun group again and press N to bring up the new file assistant. Select the Header File template from the C and C++ heading, and name the file
BIDConstants.h.
We have two more files to go. If you look at Figure 16–5, you can see that we offer an option to select a random color. UIColor doesn’t have a method to return a random color, so we’ll need to write code to do that. We could put that code into our controller class, but because we’re savvy Objective-C programmers, we’ll put it into a category on UIColor.
Again, select the QuartzFun folder and press N to bring up the new file assistant. Select the Objective-C category from the Cocoa Touch heading and hit Next. When prompted, name the category BIDRandom and make it a Category on UIColor. Click Next, and save the file into your project folder.
You should now have a new pair of files named UIColor+BIDRandom.h and
UIColor+BIDRandom.m for your category.
Creating a Random Color
Let’s tackle the category first. Add the following line to UIColor+BIDRandom.h:
#import <UIKit/UIKit.h>
@interface UIColor (BIDRandom)
+ (UIColor *)randomColor;
@end
Now, switch over to UIColor+BIDRandom.m, and add this code:
#import "UIColor+BIDRandom.h"
@implementation UIColor (BIDRandom)
+ (UIColor *)randomColor { static BOOL seeded = NO; if (!seeded) {
seeded = YES; srandom(time(NULL));
}
CGFloat red = (CGFloat)random() / (CGFloat)RAND_MAX; CGFloat blue = (CGFloat)random() / (CGFloat)RAND_MAX; CGFloat green = (CGFloat)random() / (CGFloat)RAND_MAX;
return [UIColor colorWithRed:red green:green blue:blue alpha:1.0f];
}
@end
www.it-ebooks.info
574 |
CHAPTER 16: Drawing with Quartz and OpenGL |
This is fairly straightforward. We declare a static variable that tells us if this is the first time through the method. The first time this method is called during an application’s run, we will seed the random-number generator. Doing this here means we don’t need to rely on the application doing it somewhere else, and as a result, we can reuse this category in other iOS projects.
Once we’ve made sure the random-number generator is seeded, we generate three random CGFloats with a value between 0.0 and 1.0, and use those three values to create a new color. We set alpha to 1.0 so that all generated colors will be opaque.
Defining Application Constants
Next, we’ll define constants for each of the options that the user can select using the segmented controllers. Single-click BIDConstants.h, and add the following code:
#ifndef QuartzFun_BIDConstants_h #define QuartzFun_BIDConstants_h
typedef enum { kLineShape = 0, kRectShape, kEllipseShape, kImageShape
} ShapeType;
typedef enum { kRedColorTab = 0, kBlueColorTab, kYellowColorTab, kGreenColorTab, kRandomColorTab
} ColorTabIndex;
#define degreesToRadian(x) (M_PI * (x) / 180.0)
#endif
To make our code more readable, we’ve declared two enumeration types using typedef. One will represent the shape options available in our application; the other will represent the various color options available. The values these constants hold will correspond to segments on the two segmented controllers we’ll create in our application.
NOTE: Just in case you haven’t seen this form before, the purpose of the #ifndef compiler directive is to first test if QuartzFun_BIDConstants_h is defined and, if not, to define it. Why not just put in the #define? This way, if a .h file is included more than once, either directly or via other .h files, the directive won’t be duplicated.
www.it-ebooks.info
CHAPTER 16: Drawing with Quartz and OpenGL |
575 |
Implementing the QuartzFunView Skeleton
Since we’re going to do our drawing in a subclass of UIView, let’s set up that class with everything it needs except for the actual code to do the drawing, which we’ll add later. Single-click BIDQuartzFunView.h, and add the following code:
#import <UIKit/UIKit.h>
#import "BIDConstants.h"
@interface BIDQuartzFunView : UIView
@property (nonatomic) CGPoint firstTouch; @property (nonatomic) CGPoint lastTouch;
@property (strong, nonatomic) UIColor *currentColor; @property (nonatomic) ShapeType shapeType;
@property (nonatomic, strong) UIImage *drawImage; @property (nonatomic) BOOL useRandomColor;
@end
First, we import the BIDConstants.h header we just created so we can make use of our enumeration values. We then declare our properties. The first two will track the user’s finger as it drags across the screen. We’ll store the location where the user first touches the screen in firstTouch. We’ll store the location of the user’s finger while dragging and when the drag ends in lastTouch. Our drawing code will use these two variables to determine where to draw the requested shape.
Next, we define a color to hold the user’s color selection and a ShapeType to keep track of the shape the user wants to draw. After that is a UIImage property that will hold the image to be drawn on the screen when the user selects the rightmost toolbar item on the bottom toolbar (see Figure 16–6). The last property is a Boolean that will be used to keep track of whether the user is requesting a random color.
www.it-ebooks.info
576 |
CHAPTER 16: Drawing with Quartz and OpenGL |
Figure 16–6. When drawing a UIImage to the screen, notice that the color control disappears. Can you tell which app is running on the tiny iPhone?
Switch to BIDQuartzFunView.m. We have several changes we need to make in this file. First, we’re going to need access to the randomColor category method we wrote earlier in the chapter, at the top of the file. We’ll also need to synthesize our properties. So add these lines directly below the existing import statement:
#import "UIColor+BIDRandom.h"
and add this one right after the @implementation declaration:
@synthesize firstTouch, lastTouch, currentColor, drawImage, useRandomColor, shapeType;
The template gave us a method called initWithFrame:, but we won’t be using that. Keep in mind that object instances in nibs are stored as archived objects, which is the same mechanism we used in Chapter 13 to archive and load our objects to disk. As a result, when an object instance is loaded from a nib, neither init nor initWithFrame: is ever called. Instead, initWithCoder: is used, so this is where we need to add any initialization code. In our case, we’ll set the initial color value to red, initialize useRandomColor to NO, and load the image file that we’re going to draw later in the chapter. Delete the existing stub implementation of initWithFrame:, and replace it with the following method:
www.it-ebooks.info
CHAPTER 16: Drawing with Quartz and OpenGL |
577 |
-(id)initWithCoder:(NSCoder*)coder {
if (self = [super initWithCoder:coder]) { currentColor = [UIColor redColor]; useRandomColor = NO;
self.drawImage = [UIImage imageNamed:@"iphone.png"] ;
}
return self;
}
After initWithCoder:, we need to add a few more methods to respond to the user’s touches. Insert the following three methods after initWithCoder:.
#pragma mark - Touch Handling
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { if (useRandomColor) {
self.currentColor = [UIColor randomColor];
}
UITouch *touch = [touches anyObject]; firstTouch = [touch locationInView:self]; lastTouch = [touch locationInView:self]; [self setNeedsDisplay];
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { UITouch *touch = [touches anyObject];
lastTouch = [touch locationInView:self];
[self setNeedsDisplay];
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event { UITouch *touch = [touches anyObject];
lastTouch = [touch locationInView:self];
[self setNeedsDisplay];
}
These three methods are inherited from UIView (but actually declared in UIView‘s parent UIResponder). They can be overridden to find out where the user is touching the screen. They work as follows:
touchesBegan:withEvent: is called when the user’s finger first touches the screen. In that method, we change the color if the user has selected a random color using the new randomColor method we added to UIColor earlier. After that, we store the current location so that we know where the user first touched the screen, and we indicate that our view needs to be redrawn by calling setNeedsDisplay on self.
www.it-ebooks.info