Creating the Detail View Controller

Một phần của tài liệu beginning iphone 3 development exploring the iphone sdk phần 6 pdf (Trang 37 - 56)

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 PresidentDetailController.h, and make the following changes:

#import <Foundation/Foundation.h>

@class President;

Download at Boykma.Com

#define kNumberOfEditableRows 4

#define kNameRowIndex 0

#define kFromYearRowIndex 1

#define kToYearRowIndex 2

#define kPartyIndex 3

#define kLabelTag 4096

@interface PresidentDetailController : NSObject {

@interface PresidentDetailController : UITableViewController <UITextFieldDelegate> {

President *president;

NSArray *fieldLabels;

NSMutableDictionary *tempValues;

UITextField *textFieldBeingEdited;

}

@property (nonatomic, retain) President *president;

@property (nonatomic, retain) NSArray *fieldLabels;

@property (nonatomic, retain) NSMutableDictionary *tempValues;

@property (nonatomic, retain) UITextField *textFieldBeingEdited;

- (IBAction)cancel:(id)sender;

- (IBAction)save:(id)sender;

- (IBAction)textFieldDone:(id)sender;

@end

Well, now, what the heck is going on here? This is new. In all our previous table view exam- ples, each table row corresponded to a single row in an array. The array provided all the data the table needed. So, 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 presidents, by name, and 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 have to 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 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 have 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 President object. This is the object that we will actually be editing using this view, and it’s set in the tableView:didSelectRowAt IndexPath: of our parent controller based on the row selected there. When the user taps the row for Thomas Jefferson, the PresidentsViewController will create an instance of the PresidentDetailController. The PresidentsViewController will then set the

president property of that instance to the object that represents Thomas Jefferson, and push the newly created instance of PresidentDetailController onto the navigation stack.

The second instance variable, fieldLabels, is an array that holds a list of labels that cor- respond 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 in a minute.

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 back to it.

Instead, what we will do is store any value that gets changed in our new mutable dictionary,

tempValues. So if, for example, the user edited the Name: field and then tapped the Party:

field to start editing that one, the PresidentDetailController would get notified at that time that the Name: field had been edited, because it is the text field’s delegate.

When the PresidentDetailController gets 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’d 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, and if they save, we copy the changed values over to president. Next up is a pointer to a UITextField, named textFieldBeingEdited. The moment the users click in one of the PresidentDetailController text fields, textFieldBeingEdited

is set to point to that text field. Why do we need this text field pointer? We have an interest- ing timing problem, and textFieldBeingEdited 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

Download at Boykma.Com

field that was being edited loses first responder status, and the delegate method

textFieldDidEndEditing: is called. You’ll see textFieldDidEndEditing: in a few pages when we enter the code for PresidentDetailController.m. In this case,

textFieldDidEndEditing: takes the new value of the text field and stores it in

tempValues.

The second way the 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 gets called. In both meth- ods, the PresidentDetailController 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.

textFieldDidEndEditing:, the delegate method we discussed in the previous para- graph, does have access to the text field, since the text field is passed in as a parameter.

That’s where textFieldBeingEdited comes in. The cancel: action method ignores

textFieldBeingEdited, since the user did not want to save changes, so the changes can be lost with no problem. But the save: method does care about those changes and needs a way to save them.

Since textFieldBeingEdited 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 PresidentDetailController 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. That’s OK; we’ve saved that sucker already, so all is cool.

Single-click PresidentDetailController.m, and make the following changes:

#import "PresidentDetailController.h"

#import "President.h"

@implementation PresidentDetailController

@synthesize president;

@synthesize fieldLabels;

@synthesize tempValues;

@synthesize textFieldBeingEdited;

-(IBAction)cancel:(id)sender {

[self.navigationController popViewControllerAnimated:YES];

}

- (IBAction)save:(id)sender {

if (textFieldBeingEdited != nil) {

NSNumber *tagAsNum= [[NSNumber alloc]

initWithInt:textFieldBeingEdited.tag];

[tempValues setObject:textFieldBeingEdited.text forKey: tagAsNum];

[tagAsNum release];

}

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 {

NSArray *array = [[NSArray alloc] initWithObjects:@"Name:", @"From:", @"To:", @"Party:", nil];

self.fieldLabels = array;

[array release];

UIBarButtonItem *cancelButton = [[UIBarButtonItem alloc]

initWithTitle:@"Cancel"

style:UIBarButtonItemStylePlain target:self

action:@selector(cancel:)];

self.navigationItem.leftBarButtonItem = cancelButton;

[cancelButton release];

UIBarButtonItem *saveButton = [[UIBarButtonItem alloc]

initWithTitle:@"Save"

Download at Boykma.Com

style:UIBarButtonItemStyleDone target:self

action:@selector(save:)];

self.navigationItem.rightBarButtonItem = saveButton;

[saveButton release];

NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];

self.tempValues = dict;

[dict release];

[super viewDidLoad];

}

- (void)dealloc {

[textFieldBeingEdited release];

[tempValues release];

[president release];

[fieldLabels release];

[super dealloc];

}

#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] autorelease];

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];

[label release];

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;

}

label.text = [fieldLabels objectAtIndex:row];

NSNumber *rowAsNum = [[NSNumber alloc] initWithInt: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 (textFieldBeingEdited == textField) textFieldBeingEdited = nil;

Download at Boykma.Com

textField.tag = row;

[rowAsNum release];

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.textFieldBeingEdited = textField;

}

- (void)textFieldDidEndEditing:(UITextField *)textField {

NSNumber *tagAsNum = [[NSNumber alloc] initWithInt:textField.tag];

[tempValues setObject:textField.text forKey:tagAsNum];

[tagAsNum release];

}

@end

The first new method is our cancel: action method. This gets 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. Ordinar- ily, 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 { NavAppDelegate *delegate =

[[UIApplication sharedApplication] delegate];

[delegate.navController popViewControllerAnimated:YES];

}

The next method is save:, which gets 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 well 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 textFieldBeingEdited. If

textFieldBeingEdited is not nil, we grab its value and stick it in tempValues:

if (textFieldBeingEdited != nil) {

NSNumber *tfKey= [[NSNumber alloc] initWithInt:

textFieldBeingEdited.tag];

[tempValues setObject:textFieldBeingEdited.text forKey:tfKey];

[tagAsNum release];

}

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;

} }

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 of the navigation stack, sending the user back up to the list of presidents:

NavAppDelegate *delegate =

[[UIApplication sharedApplication] delegate];

[delegate.navController popViewControllerAnimated:YES];

There’s one other thing we have to do here, which is to 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 PresidentsViewController table, if we don’t have that table reload its data, it will continue to show the old value.

Download at Boykma.Com

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 con- sistent 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;

[array release];

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, for a but- ton 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 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;

[cancelButton release];

UIBarButtonItem *saveButton = [[UIBarButtonItem alloc]

initWithTitle:@"Save"

style:UIBarButtonItemStyleDone target:self

action:@selector(save:)];

self.navigationItem.rightBarButtonItem = saveButton;

[saveButton release];

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’d have no easy way to roll back to the original data when the user tapped Cancel.

NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];

self.tempValues = dict;

[dict release];

[super viewDidLoad];

We can skip over the dealloc method and the first data source method, as there are is noth- ing new under the sun there. We do need to stop and chat about tableView:cellForRowAt IndexPath:, 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] autorelease];

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. It’s pretty straightforward:

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];

[label release];

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 in a moment, we’ve implemented two text field delegate methods in this class. Those methods will get called by the text fields on all rows when the user begins and ends editing the text they contain. We also set the key- board’s return key type, which is how we specify the text for the key in the bottom-right of

Download at Boykma.Com

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;

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 con- nections inspector in Interface Builder to File’s Owner and selecting an action method. Since we don’t have a nib file, we have to do it programmatically, but the result is the same.

When we’re all done 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’ve either got 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 done, 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;

}

Một phần của tài liệu beginning iphone 3 development exploring the iphone sdk phần 6 pdf (Trang 37 - 56)

Tải bản đầy đủ (PDF)

(58 trang)