Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Beginning iOS5 Development.pdf
Скачиваний:
7
Добавлен:
09.05.2015
Размер:
15.6 Mб
Скачать

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

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]