- •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
336 |
CHAPTER 9: Navigation Controllers and Table Views |
- (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; [self.tableView reloadData];
}
There’s one other change from the last time we created a detail view. It’s in the last method, tableView:didSelectRowAtIndexPath:. When we created the Disclosure Button view, we reused the same child controller every time and just changed its values. That’s relatively easy to do when you have a nib with outlets. When you’re using a table view to implement your detail view, the methods that fire the first time and the ones that fire subsequent times are different. Also, the table cells that are used to display and change the data are reused. The combination of these two details means your code can get very complex if you’re trying to make it behave exactly the same way every time and to make sure that you are able to keep track of all the changes. Therefore, it’s well worth the bit of additional overhead from allocating and releasing new controller objects to reduce the complexity of our controller class.
Let’s look at the detail controller, because that’s where the bulk of the new stuff is this time. This new controller is pushed onto the navigation stack when the user taps one of the rows in the BIDPresidentsViewController table to allow data entry for that president. Let’s implement the detail view now.
Creating the Detail View Controller
Please fasten your seatbelts, ladies and gentlemen. We’re expecting a little turbulence ahead. Air sickness bags are located in the seat pocket in front of you.
This next controller is just a little on the gnarly side, but we’ll get through it safely. Please remain seated. Single-click BIDPresidentDetailController.h, and make the following changes:
#import <UIKit/UIKit.h>
@class BIDPresident; |
|
#define kNumberOfEditableRows |
4 |
#define kNameRowIndex |
0 |
#define kFromYearRowIndex |
1 |
#define kToYearRowIndex |
2 |
#define kPartyIndex |
3 |
#define kLabelTag |
4096 |
@interface BIDPresidentDetailController : UITableViewController
<UITextFieldDelegate>
@property (strong, nonatomic) BIDPresident *president; @property (strong, nonatomic) NSArray *fieldLabels;
@property (strong, nonatomic) NSMutableDictionary *tempValues; @property (strong, nonatomic) UITextField *currentTextField;
-(IBAction)cancel:(id)sender;
-(IBAction)save:(id)sender;
www.it-ebooks.info
CHAPTER 9: Navigation Controllers and Table Views |
337 |
- (IBAction)textFieldDone:(id)sender;
@end
What the heck is going on here? This is new. In all our previous table view examples, each table row corresponded to a single row in an array. The array provided all the data the table needed. For example, our table of Pixar movies was driven by an array of strings, each string containing the title of a single Pixar movie.
Our presidents example features two different tables. One is a list of president names, and it is driven by an array with one president per row. The second table implements a detail view of a selected president. Since this table has a fixed number of fields, instead of using an array to supply data to this table, we define a series of constants we will use in our table data source methods. These constants define the number of editable fields, along with the index value for the row that will hold each of those properties.
There’s also a constant called kLabelTag that we’ll use to retrieve the UILabel from the cell so that we can set the label correctly for the row. Shouldn’t there be another tag for the UITextField? Normally, yes, but we will need to use the tag property of the text field for another purpose. We’ll use another slightly less convenient mechanism to retrieve the text field when we need to set its value. Don’t worry if that seems confusing; everything should become clear when we actually write the code.
You should notice that this class conforms to three protocols this time: the table data source and delegate protocols (which this class inherits because it’s a subclass of
UITableViewController) and a new one, UITextFieldDelegate. By conforming to
UITextFieldDelegate, we’ll be notified when a user makes a change to a text field so that we can save the field’s value. This application doesn’t have enough rows for the table to ever need to scroll, but in many applications, a text field could scroll off the screen, and perhaps be deallocated or reused. If the text field is lost, the value stored in it is lost, so saving the value when the user makes a change is the way to go.
Down a little further, we declare a pointer to a BIDPresident object. This is the object that we will actually be editing using this view, and it’s set in the tableView:didSelectRowAtIndexPath: of our parent controller based on the row selected there. When the user taps the row for Thomas Jefferson, for example, the
BIDPresidentsViewController will create an instance of the BIDPresidentDetailController. The BIDPresidentsViewController will then set the president property of that instance to the object that represents Thomas Jefferson, and push the newly created instance of BIDPresidentDetailController onto the navigation stack.
The second instance variable, fieldLabels, is an array that holds a list of labels that correspond to the constants kNameRowIndex, kFromYearRowIndex, kToYearRowIndex, and kPartyIndex. For example, kNameRowIndex is defined as 0. So, the label for the row that shows the president’s name is stored at index 0 in the fieldLabels array. You’ll see this in action when we get to it in code.
Next, we define a mutable dictionary, tempValues, that will hold values from fields the user changes. We don’t want to make the changes directly to the president object because if the user selects the Cancel button, we need the original data so we can go
www.it-ebooks.info
338 |
CHAPTER 9: Navigation Controllers and Table Views |
back to it. Instead, we will store any value that is changed in our new mutable dictionary, tempValues. For example, if the user edited the Name: field and then tapped the Party: field to start editing that one, the BIDPresidentDetailController would be notified at that time that the Name: field had been edited, because it is the text field’s delegate.
When the BIDPresidentDetailController is notified of the change, it stores the new value in the dictionary using the name of the property it represents as the key. In our example, we would store a change to the Name: field using the key @"name". That way, regardless of whether users save or cancel, we have the data we need to handle it. If the users cancel, we just discard this dictionary; if they save, we copy the changed values over to president.
Next up is a pointer to a UITextField, named currentTextField. The moment the users click in one of the BIDPresidentDetailController text fields, currentTextField is set to point to that text field. Why do we need this text field pointer? We have an interesting timing problem, and currentTextField is the solution.
Users can take one of two basic paths to finish editing a text field. First, they can touch another control or text field that becomes first responder. In this case, the text field that was being edited loses first responder status, and the delegate method textFieldDidEndEditing: is called. textFieldDidEndEditing: takes the new value of the text field and stores it in tempValues.
The second way that users can finish editing a text field is by tapping the Save or Cancel button. When they do this, the save: or cancel: action method is called. In both methods, the BIDPresidentDetailController view must be popped off the stack, since both the save and cancel actions end the editing session. This presents a problem. The save: and cancel: action methods do not have a simple way of finding the just-edited text field to save the data.
The delegate method textFieldDidEndEditing: does have access to the text field, since the text field is passed in as a parameter. That’s where currentTextField comes in. The cancel: action method ignores currentTextField, since the user did not want to save changes, so the changes can be lost without causing any problems. But the save: method does care about those changes and needs a way to save them.
Since currentTextField is maintained as a pointer to the current text field being edited, save: uses that pointer to copy the value in the text field to tempValues. Now, save: can do its job and pop the BIDPresidentDetailController view off the stack, which will bring our list of presidents back to the top of the stack. When the view is popped off the stack, the text field and its value are lost. But since we’ve saved that sucker already, all is cool.
Single-click BIDPresidentDetailController.m, and make the following changes:
#import "BIDPresidentDetailController.h"
#import "BIDPresident.h"
@implementation BIDPresidentDetailController
@synthesize president; @synthesize fieldLabels;
www.it-ebooks.info
CHAPTER 9: Navigation Controllers and Table Views |
339 |
@synthesize tempValues; @synthesize currentTextField;
- (IBAction)cancel:(id)sender {
[self.navigationController popViewControllerAnimated:YES];
}
- (IBAction)save:(id)sender {
if (currentTextField != nil) {
NSNumber *tagAsNum = [NSNumber numberWithInt:currentTextField.tag]; [tempValues setObject:currentTextField.text forKey:tagAsNum];
}
for (NSNumber *key in [tempValues allKeys]) { switch ([key intValue]) {
case kNameRowIndex:
president.name = [tempValues objectForKey:key]; break;
case kFromYearRowIndex:
president.fromYear = [tempValues objectForKey:key]; break;
case kToYearRowIndex:
president.toYear = [tempValues objectForKey:key]; break;
case kPartyIndex:
president.party = [tempValues objectForKey:key]; default:
break;
}
}
[self.navigationController popViewControllerAnimated:YES];
NSArray *allControllers = self.navigationController.viewControllers; UITableViewController *parent = [allControllers lastObject]; [parent.tableView reloadData];
}
- (IBAction)textFieldDone:(id)sender { [sender resignFirstResponder];
}
#pragma mark -
- (void)viewDidLoad { [super viewDidLoad];
NSArray *array = [[NSArray alloc] initWithObjects:@"Name:", @"From:", @"To:", @"Party:", nil];
self.fieldLabels = array;
UIBarButtonItem *cancelButton = [[UIBarButtonItem alloc] initWithTitle:@"Cancel" style:UIBarButtonItemStylePlain target:self action:@selector(cancel:)];
self.navigationItem.leftBarButtonItem = cancelButton;
www.it-ebooks.info
340 |
CHAPTER 9: Navigation Controllers and Table Views |
UIBarButtonItem *saveButton = [[UIBarButtonItem alloc] initWithTitle:@"Save" style:UIBarButtonItemStyleDone target:self action:@selector(save:)];
self.navigationItem.rightBarButtonItem = saveButton;
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init]; self.tempValues = dict;
}
#pragma mark -
#pragma mark Table Data Source Methods
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return kNumberOfEditableRows;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *PresidentCellIdentifier = @"PresidentCellIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier: PresidentCellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:PresidentCellIdentifier];
UILabel *label = [[UILabel alloc] initWithFrame: CGRectMake(10, 10, 75, 25)];
label.textAlignment = UITextAlignmentRight; label.tag = kLabelTag;
label.font = [UIFont boldSystemFontOfSize:14]; [cell.contentView addSubview:label];
UITextField *textField = [[UITextField alloc] initWithFrame: CGRectMake(90, 12, 200, 25)];
textField.clearsOnBeginEditing = NO; [textField setDelegate:self]; textField.returnKeyType = UIReturnKeyDone; [textField addTarget:self
action:@selector(textFieldDone:)
forControlEvents:UIControlEventEditingDidEndOnExit]; [cell.contentView addSubview:textField];
}
NSUInteger row = [indexPath row];
UILabel *label = (UILabel *)[cell viewWithTag:kLabelTag]; UITextField *textField = nil;
for (UIView *oneView in cell.contentView.subviews) { if ([oneView isMemberOfClass:[UITextField class]])
textField = (UITextField *)oneView;
}
www.it-ebooks.info
CHAPTER 9: Navigation Controllers and Table Views |
341 |
label.text = [fieldLabels objectAtIndex:row]; NSNumber *rowAsNum = [NSNumber numberWithInt:row]; switch (row) {
case kNameRowIndex:
if ([[tempValues allKeys] containsObject:rowAsNum]) textField.text = [tempValues objectForKey:rowAsNum];
else
textField.text = president.name; break;
case kFromYearRowIndex:
if ([[tempValues allKeys] containsObject:rowAsNum]) textField.text = [tempValues objectForKey:rowAsNum];
else
textField.text = president.fromYear; break;
case kToYearRowIndex:
if ([[tempValues allKeys] containsObject:rowAsNum]) textField.text = [tempValues objectForKey:rowAsNum];
else
textField.text = president.toYear; break;
case kPartyIndex:
if ([[tempValues allKeys] containsObject:rowAsNum]) textField.text = [tempValues objectForKey:rowAsNum];
else
textField.text = president.party; default:
break;
}
if (currentTextField == textField) { currentTextField = nil;
}
textField.tag = row; return cell;
}
#pragma mark -
#pragma mark Table Delegate Methods
- (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath {
return nil;
}
#pragma mark Text Field Delegate Methods
- (void)textFieldDidBeginEditing:(UITextField *)textField { self.currentTextField = textField;
}
- (void)textFieldDidEndEditing:(UITextField *)textField { NSNumber *tagAsNum = [NSNumber numberWithInt:textField.tag]; [tempValues setObject:textField.text forKey:tagAsNum];
}
@end
www.it-ebooks.info
342 |
CHAPTER 9: Navigation Controllers and Table Views |
The first new method is our cancel: action method. This is called, appropriately enough, when the user taps the Cancel button. When the Cancel button is tapped, the current view will be popped off the stack, and the previous view will rise to the top of the stack. Ordinarily, that job would be handled by the navigation controller, but a little later in the code, we’re going to manually set the left bar button item. This means we’re replacing the button that the navigation controller uses for that purpose. We can pop the current view off the stack by getting a reference to the navigation controller and telling it to do just that.
- (IBAction)cancel:(id)sender {
[self.navigationController popViewControllerAnimated:YES];
}
The next method is save:, which is called when the user taps the Save button. When the Save button is tapped, the values that the user has entered have already been stored in the tempValues dictionary, unless the keyboard is still visible and the cursor is still in one of the text fields. In that case, there may be changes to that text field that have not yet been put into our tempValues dictionary. To account for this, the first thing the save: method does is check to see if there is a text field that is currently being edited. Whenever the user starts editing a text field, we store a pointer to that text field in currentTextField. If currentTextField is not nil, we grab its value and stick it in tempValues.
if (currentTextField != nil) {
NSNumber *tfKey = [NSNumber numberWithInt:currentTextField.tag]; [tempValues setObject:currentTextField.text forKey:tfKey];
}
We then use fast enumeration to step through all the key values in the dictionary, using the row numbers as keys. We can’t store raw datatypes like int in an NSDictionary, so we create NSNumber objects based on the row number and use those instead. We use intValue to turn the number represented by key back into an int, and then use a switch on that value using the constants we defined earlier and assign the appropriate value from the tempValues array back to the designated field on our president object.
for (NSNumber *key in [tempValues allKeys]) { switch ([key intValue]) {
case kNameRowIndex:
president.name = [tempValues objectForKey:key]; break;
case kFromYearRowIndex:
president.fromYear = [tempValues objectForKey:key]; break;
case kToYearRowIndex:
president.toYear = [tempValues objectForKey:key]; break;
case kPartyIndex:
president.party = [tempValues objectForKey:key]; default:
break;
}
}
www.it-ebooks.info
CHAPTER 9: Navigation Controllers and Table Views |
343 |
Now, our president object has been updated, and we need to move up a level in the view hierarchy. Tapping a Save or Done button on a detail view should generally bring the user back up to the previous level, so we grab our application delegate and use its navController outlet to pop ourselves off the navigation stack, sending the user back up to the list of presidents:
[self.navigationController popViewControllerAnimated:YES];
There’s one other thing we need to do here: tell our parent view’s table to reload its data. Because one of the fields that the user can edit is the name field, which is displayed in the BIDPresidentsViewController table, if we don’t have that table reload its data, it will continue to show the old value.
UINavigationController *navController = [delegate navController]; NSArray *allControllers = navController.viewControllers; UITableViewController *parent = [allControllers lastObject]; [parent.tableView reloadData];
The third action method will be called when the user taps the Done button on the keyboard. Without this method, the keyboard won’t retract when the user taps Done. This approach isn’t strictly necessary in our application, since the four rows that can be edited here fit in the area above the keyboard. That said, you’ll need this method if you add a row or in a future application that requires more screen real estate. It’s a good idea to keep the behavior consistent from application to application, even if doing so is not critical to your application’s functionality.
- (IBAction)textFieldDone:(id)sender { [sender resignFirstResponder];
}
The viewDidLoad method doesn’t contain anything too surprising. We create the array of field names and assign it the fieldLabels property.
NSArray *array = [[NSArray alloc] initWithObjects:@"Name:", @"From:", @"To:", @"Party:", nil];
self.fieldLabels = array;
Next, we create two buttons and add them to the navigation bar. We put the Cancel button in the left bar button item spot, which supplants the navigation button put there automatically. We put the Save button in the right spot and assign it the style UIBarButtonItemStyleDone. This style was specifically designed for this occasion—as a button users tap when they are happy with their changes and ready to leave the view. A button with this style will be blue instead of gray, and it usually will carry a label of Save or Done.
UIBarButtonItem *cancelButton = [[UIBarButtonItem alloc] initWithTitle:@"Cancel" style:UIBarButtonItemStylePlain
target:self
action:@selector(cancel:)]; self.navigationItem.leftBarButtonItem = cancelButton;
UIBarButtonItem *saveButton = [[UIBarButtonItem alloc] initWithTitle:@"Save" style:UIBarButtonItemStyleDone
www.it-ebooks.info
344 |
CHAPTER 9: Navigation Controllers and Table Views |
target:self
action:@selector(save:)]; self.navigationItem.rightBarButtonItem = saveButton;
Finally, we create a new mutable dictionary and assign it to tempValues so that we have a place to stick the changed values. If we made the changes directly to the president object, we would have no easy way to roll back to the original data if the user tapped
Cancel.
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init]; self.tempValues = dict;
We can skip over the first data source method, as there is nothing new under the sun there. We do need to stop and chat about tableView:cellForRowAtIndexPath:, however, because there are a few gotchas there. The first part of the method is exactly like every other tableView:cellForRowAtIndexPath: method we’ve written.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *PresidentCellIdentifier = @"PresidentCellIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier: PresidentCellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:PresidentCellIdentifier];
When we create a new cell, we create a label, make it right-aligned and bold, and assign it a tag so that we can retrieve it again later. Next, we add it to the cell’s contentView and release it.
UILabel *label = [[UILabel alloc] initWithFrame: CGRectMake(10, 10, 75, 25)];
label.textAlignment = UITextAlignmentRight; label.tag = kLabelTag;
label.font = [UIFont boldSystemFontOfSize:14]; [cell.contentView addSubview:label];
After that, we create a new text field. The user actually types in this field. We set it so it does not clear the current value when editing, so we don’t lose the existing data, and we set self as the text field’s delegate. By setting the text field’s delegate to self, we can get notified by the text field when certain events occur by implementing appropriate methods from the UITextFieldDelegate protocol. As you’ll see soon, we’ve implemented two text field delegate methods in this class. Those methods will be called by the text fields on all rows when the user begins and ends editing the text they contain. We also set the keyboard’s return key type, which is how we specify the text for the key in the bottom right of the keyboard. The default value is Return, but since we have only single-line fields, we want the key to say Done instead, so we pass
UIReturnKeyDone.
UITextField *textField = [[UITextField alloc] initWithFrame: CGRectMake(90, 12, 200, 25)];
textField.clearsOnBeginEditing = NO; [textField setDelegate:self];
textField.returnKeyType = UIReturnKeyDone;
www.it-ebooks.info
CHAPTER 9: Navigation Controllers and Table Views |
345 |
After that, we tell the text field to call our textFieldDone: method on the Did End on Exit event. This is exactly the same thing as dragging from the Did End on Exit event in the connections inspector in Interface Builder to File’s Owner and selecting an action method. Since we don’t have a nib file, we must do it programmatically, but the result is the same.
When we’re finished configuring the text field, we add it to the cell’s content view. Notice, however, that we did not set a tag before we added it to that view.
[textField addTarget:self action:@selector(textFieldDone:)
forControlEvents:UIControlEventEditingDidEndOnExit]; [cell.contentView addSubview:textField];
}
At this point, we know that we have either a brand-new cell or a reused cell, but we don’t know which. The first thing we do is figure out which row this darn cell is going to represent.
NSUInteger row = [indexPath row];
Next, we need to get a reference to the label and the text field from inside this cell. The label is easy; we just use the tag we assigned to it to retrieve it from cell.
UILabel *label = (UILabel *)[cell viewWithTag:kLabelTag];
The text field, however, isn’t going to be quite as easy, because we need the tag in order to tell our text field delegates which text field is calling them. So, we’re going to rely on the fact that there’s only one text field that is a subview of our cell’s contentView. We’ll use fast enumeration to work through all of its subviews, and when we find a text field, we assign it to the pointer we declared a moment earlier. When the loop is finished, the textField pointer should be pointing to the one and only text field contained in this cell.
UITextField *textField = nil;
for (UIView *oneView in cell.contentView.subviews) { if ([oneView isMemberOfClass:[UITextField class]])
textField = (UITextField *)oneView;
}
Now that we have pointers to both the label and the text field, we can assign them the correct values based on which field from the president object this row represents. Once again, the label gets its value from the fieldLabels array.
label.text = [fieldLabels objectAtIndex:row];
To assign the value to the text field, we need to first check to see if there is a value in the tempValues dictionary corresponding to this row. If there is, we assign it to the text field. If there isn’t any corresponding value in tempValues, we know there have been no changes entered for this field, so we assign this field the corresponding value from president.
NSNumber *rowAsNum = [NSNumber numberWithInt:row]; switch (row) {
case kNameRowIndex:
if ([[tempValues allKeys] containsObject:rowAsNum])
www.it-ebooks.info
346 CHAPTER 9: Navigation Controllers and Table Views
textField.text = [tempValues objectForKey:rowAsNum];
else
textField.text = president.name; break;
case kFromYearRowIndex:
if ([[tempValues allKeys] containsObject:rowAsNum]) textField.text = [tempValues objectForKey:rowAsNum];
else
textField.text = president.fromYear; break;
case kToYearRowIndex:
if ([[tempValues allKeys] containsObject:rowAsNum]) textField.text = [tempValues objectForKey:rowAsNum];
else
textField.text = president.toYear; break;
case kPartyIndex:
if ([[tempValues allKeys] containsObject:rowAsNum]) textField.text = [tempValues objectForKey:rowAsNum];
else
textField.text = president.party;
default:
break;
}
If the field we’re using is the one that is currently being edited, that’s an indication that the value we’re holding in currentTextField is no longer valid, so we set currentTextField to nil. If the text field did get released or reused, our text field delegate would have been called, and the correct value would already be in the tempValues dictionary.
if (currentTextField == textField) { currentTextField = nil;
}
Next, we set the text field’s tag to the row it represents, which will allow us to know which field is calling our text field delegate methods. And finally, we return the cell.
textField.tag = row; return cell;
}
We do implement one table delegate method this time, which is tableView:willSelectRowAtIndexPath:. Remember that this method is called before a row is selected and gives us a chance to disallow the row selection. In this view, we never want a row to appear selected. We need to know that the user selected a row so we can place a check mark next to it, but we don’t want the row to actually be highlighted. Don’t worry. A row doesn’t need to be selected for a text field on that row to be editable, so this method just keeps the row from staying highlighted after it is touched.
-(NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath {
return nil;
}
www.it-ebooks.info