Affichage des articles dont le libellé est La réutilisation du code. Afficher tous les articles
Affichage des articles dont le libellé est La réutilisation du code. Afficher tous les articles

vendredi 10 février 2012

Resuable classes réutilisables

Plus les classes réutilisables, mais cette fois, pas de moi. Joe Hewitt, de Facebook a récemment créé une projet open source appelé 320 qui contient un tas d'objets réutilisables. Ils ont l'air très poli et gentil et certainement la peine de prendre un coup d'oeil.

via Daring Fireball.

lundi 6 février 2012

Code réutilisable dans le Google Code

Conformément à une demande lecteur, j'ai créé un référentiel avec l'ensemble du code réutilisable que j'ai posté ici dans mon blog. Vous pouvez trouver le référentiel plus sur Google Code.

Je vais essayer de garder ce jour avec des corrections de bugs et d'ajouter tout nouveau code réutilisable pour le référentiel.

Sélectionnez la liste modifiable

Pour un projet que je travaillais sur, nous avions un champ de texte que les utilisateurs ont tendance à entrer dans la même poignée de valeurs de plus et plus. En effet, le fait qu'ils avaient à garder en entrant les valeurs mêmes et plus était assez frustrant de nos testeurs. Mais nous ne pouvions pas fournir une liste définie, car elle ne serait pas les mêmes valeurs pour tous les utilisateurs. Ils avaient besoin de la souplesse nécessaire pour ajouter une valeur quelconque dont ils avaient besoin, mais je voulais la commodité de ne pas avoir à entrer ceux qu'ils avaient déjà entrés. Sur une application de bureau, la réponse aurait probablement été un combo-box, ou un champ texte avec saisie prédictive qui permettrait à l'utilisateur de taper quelques caractères de la valeur et puis appuyez sur l'onglet ou le retour pour le sélectionner.

L'iPhone ne dispose pas de listes déroulantes, et le type vert serait une douleur pour mettre en œuvre et j'avais des inquiétudes qu'il pourrait obtenir sonné dans le processus d'examen (oui, Apple, votre revue les politiques sont certainement avoir un effet paralysant). La réponse je suis venu avec pour gérer cette situation était de créer un contrôleur de sélection modifiable liste. Il fonctionne exactement comme la Generic Controller liste de sélection J'ai posté il ya une semaine, sauf qu'il punaises d'un élément sur l'extrémité de la table pour permettre à l'utilisateur d'ajouter un nouvel élément à la liste:


Lorsque vous sélectionnez ce dernier élément, il utilise le Multiple Text Field Editing Controller d'inviter l'utilisateur à la nouvelle valeur:



À un certain point, je tiens à refactoriser cette classe, et le SelectionListViewcontroller dans une classe, comme il ya beaucoup de points communs entre eux, mais pour l'instant, c'est une catégorie distincte. Vous devez avoir la classe dans votre projet TextFieldEditingViewcontroller aussi, car il utilise que pour laisser l'utilisateur saisir de nouvelles valeurs.

EditableSelectionListViewController.h
//
// SelectionListViewController.h
//
// Created by Jeff LaMarche on 2/18/09.
// Copyright 2009 Jeff LaMarche Consulting. All rights reserved.
//

#import <UIKit/UIKit.h>
#import "AbstractGenericViewController.h"
#import "TextFieldEditingViewController.h"

@protocol EditableSelectionListViewControllerDelegate <NSObject>
@required
- (void)rowChosen:(NSInteger)row fromArray:(NSMutableArray *)theList;
@end


@interface EditableSelectionListViewController : AbstractGenericViewController <TextFieldEditingViewControllerDelegate>
{
NSMutableArray *list;
NSIndexPath *lastIndexPath;
NSInteger initialSelection;

id <EditableSelectionListViewControllerDelegate> delegate;
}

@property (nonatomic, retain) NSIndexPath *lastIndexPath;
@property (nonatomic, retain) NSArray *list;
@property NSInteger initialSelection;
@property (nonatomic, assign) id <EditableSelectionListViewControllerDelegate> delegate;
@end



EditableSelectionListViewController.m
//
// SelectionListViewController.m
//
// Created by Jeff LaMarche on 2/18/09.
// Copyright 2009 Jeff LaMarche Consulting. All rights reserved.
//

#import "EditableSelectionListViewController.h"


@implementation EditableSelectionListViewController
@synthesize list;
@synthesize lastIndexPath;
@synthesize initialSelection;
@synthesize delegate;
-(IBAction)save
{
[self.delegate rowChosen:[lastIndexPath row] fromArray:list];
[self.navigationController popViewControllerAnimated:YES];
}

#pragma mark -
- (id)initWithStyle:(UITableViewStyle)style
{
initialSelection = -1;
return self;
}

- (void)viewWillAppear:(BOOL)animated
{
// Check to see if user has indicated a row to be selected, and set it
if (initialSelection > - 1 && initialSelection < [list count])
{
NSUInteger newIndex[] = {0, initialSelection};
NSIndexPath *newPath = [[NSIndexPath alloc] initWithIndexes:newIndex length:2];
self.lastIndexPath = newPath;
[newPath release];
}


[super viewWillAppear:animated];
}

- (void)dealloc
{
[list release];
[lastIndexPath release];
[super dealloc];
}

#pragma mark -
#pragma mark Tableview methods
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [list count] + 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

static NSString *SelectionListCellIdentifier = @"SelectionListCellIdentifier";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:SelectionListCellIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:SelectionListCellIdentifier] autorelease];
}


NSUInteger row = [indexPath row];
NSUInteger oldRow = [lastIndexPath row];
if (row >= [list count])
{
cell.font = [UIFont boldSystemFontOfSize:19.0];
cell.text = NSLocalizedString(@"Other...", @"Other...");
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}

else
{
cell.font = [UIFont systemFontOfSize:19.0];
cell.text = [list objectAtIndex:row];
cell.accessoryType = (row == oldRow && lastIndexPath != nil) ? UITableViewCellAccessoryCheckmark : UITableViewCellAccessoryNone;

}


return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
int newRow = [indexPath row];
int oldRow = [lastIndexPath row];

if (newRow < [list count])
{
if (newRow != oldRow)
{
UITableViewCell *newCell = [tableView cellForRowAtIndexPath:indexPath];
newCell.accessoryType = UITableViewCellAccessoryCheckmark;

UITableViewCell *oldCell = [tableView cellForRowAtIndexPath: lastIndexPath];
oldCell.accessoryType = UITableViewCellAccessoryNone;

lastIndexPath = indexPath;
}

}

else
{
TextFieldEditingViewController *controller = [[TextFieldEditingViewController alloc] initWithStyle:UITableViewStyleGrouped];
controller.fieldKeys = [NSArray arrayWithObject:@"newValue"];
controller.fieldNames = [NSArray arrayWithObject:NSLocalizedString(@"New Item", @"New Item")];
controller.fieldValues = [NSArray arrayWithObject:@""];
controller.delegate = self;
[self.navigationController pushViewController:controller animated:YES];
}

[tableView deselectRowAtIndexPath:indexPath animated:YES];
}

#pragma mark -
- (void)selectRow:(NSIndexPath *)theIndexPath
{
//[self.tableView selectRowAtIndexPath:theIndexPath animated:YES scrollPosition:UITableViewScrollPositionBottom];
[self tableView:self.tableView didSelectRowAtIndexPath:theIndexPath];
}

- (void)valuesDidChange:(NSDictionary *)newValues
{
NSString *newVal = [newValues objectForKey:@"newValue"];
[list addObject:newVal];
//[self.tableView reloadData];

[list sortUsingSelector:@selector(compare:)];
NSUInteger theIndices[] = {0, [list indexOfObject:newVal]};
NSIndexPath *theIndexPath = [[NSIndexPath alloc] initWithIndexes:theIndices length:2];
[self performSelector:@selector(selectRow:) withObject:theIndexPath afterDelay:0.05];
// [self tableView:self.tableView didSelectRowAtIndexPath:theIndexPath];
[self.tableView reloadData];
}

@end




samedi 4 février 2012

Un sélecteur de meilleure date génériques

J'ai peaufiné ma classe générique sélecteur de date afin qu'il corresponde, pixel pour pixel, le sélecteur de date utilisé par Apple intégré dans des applications comme le carnet d'adresses (Contacts.app), et aussi corrigé quelques bugs dans le version précédente.



Voici le code qui l'implémente. L'utilisation est exactement le même que le version précédente.

Note: Si vous avez copié ce sujet avant 17h30 HNE, le vendredi Janvier 23, 2009, vous pouvez re-copier. Il y avait une fuite de mémoire grâce à moi d'oublier de libérer l'instance de formatage de la date.

DateViewController.h
/*
DateViewController.h
*/


#import <UIKit/UIKit.h>

@protocol DateViewDelegate <NSObject>
@required
- (void)takeNewDate:(NSDate *)newDate;
- (UINavigationController *)navController; // Return the navigation controller
@end


@interface DateViewController : UIViewController <UITableViewDelegate, UITableViewDataSource>
{
UIDatePicker *datePicker;
UITableView *dateTableView;
NSDate *date;

id <DateViewDelegate> delegate; // weak ref
}
@property (nonatomic, retain) UIDatePicker *datePicker;
@property (nonatomic, retain) UITableView *dateTableView;
@property (nonatomic, retain) NSDate *date;
@property (nonatomic, assign) id <DateViewDelegate> delegate;
-(IBAction)dateChanged;
@end


DateViewController.m
/*
DateViewController.m
*/

#import "DateViewController.h"

@implementation DateViewController
@synthesize datePicker;
@synthesize dateTableView;
@synthesize date;
@synthesize delegate;

-(IBAction)dateChanged
{
self.date = [datePicker date];
[dateTableView reloadData];
}
-(IBAction)cancel
{
[[self.delegate navController] popViewControllerAnimated:YES];
}
-(IBAction)save
{
[self.delegate takeNewDate:date];
[[self.delegate navController] popViewControllerAnimated:YES];
}
- (void)loadView
{
UIView *theView = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
self.view = theView;
[theView release];

UITableView *theTableView = [[UITableView alloc] initWithFrame:CGRectMake(0.0, 67.0, 320.0, 480.0) style:UITableViewStyleGrouped];
theTableView.delegate = self;
theTableView.dataSource = self;
[self.view addSubview:theTableView];
self.dateTableView = theTableView;
[theTableView release];

UIDatePicker *theDatePicker = [[UIDatePicker alloc] initWithFrame:CGRectMake(0.0, 200.0, 320.0, 216.0)];
theDatePicker.datePickerMode = UIDatePickerModeDate;
self.datePicker = theDatePicker;
[theDatePicker release];
[datePicker addTarget:self action:@selector(dateChanged) forControlEvents:UIControlEventValueChanged];
[self.view addSubview:datePicker];




UIBarButtonItem *cancelButton = [[UIBarButtonItem alloc]
initWithTitle:NSLocalizedString(@"Cancel", @"Cancel - for button to cancel changes")
style:UIBarButtonItemStylePlain
target:self
action:@selector(cancel)]
;
self.navigationItem.leftBarButtonItem = cancelButton;
[cancelButton release];
UIBarButtonItem *saveButton = [[UIBarButtonItem alloc]
initWithTitle:NSLocalizedString(@"Save", @"Save - for button to save changes")
style:UIBarButtonItemStylePlain
target:self
action:@selector(save)]
;
self.navigationItem.rightBarButtonItem = saveButton;
[saveButton release];

self.view.backgroundColor = [UIColor groupTableViewBackgroundColor];

}

- (void)viewWillAppear:(BOOL)animated
{
if (self.date != nil)
[self.datePicker setDate:date animated:YES];
else
[self.datePicker setDate:[NSDate date] animated:YES];

[super viewWillAppear:animated];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void)dealloc
{
[datePicker release];
[dateTableView release];
[date release];
[super dealloc];
}
#pragma mark -
#pragma mark Table View Methods
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

static NSString *DateCellIdentifier = @"DateCellIdentifier";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:DateCellIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:DateCellIdentifier] autorelease];
cell.font = [UIFont systemFontOfSize:17.0];
cell.textColor = [UIColor colorWithRed:0.243 green:0.306 blue:0.435 alpha:1.0];
}

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"MMMM dd, yyyy"];
cell.text = [formatter stringFromDate:date];
[formatter release];


return cell;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return 1;
}
@end


vendredi 3 février 2012

Une date réutilisables Drill-Down Controller

L'autre jour, j'ai posté un réutilisables à base de tableaux de drill-down de contrôleur. Aujourd'hui, je poste un autre dans ma série de re-utilisables de drill-down contrôleurs: une date réutilisables drill-down.

Pour utiliser ce contrôleur, conçu pour être utilisé comme un drill-down dans une application de navigation basée sur tout ce que vous avez à faire est de créer une instance de la classe, et mis en déléguer cette instance à l'auto, puis réglez la date à afficher quand il est d'abord montré, comme ceci:

DateViewController *controller = [[DateViewController alloc] init];
controller.delegate = self;
controller.date = theDateToBeEdited;
[delegate.rootController pushViewController:controller animated:YES];
[controller release];

Ensuite, mettre en œuvre cette méthode déléguée:

- (void)takeNewDate:(NSDate *)newDate
{
myObject.date = newDate;
}

Maintenant, lorsque le contrôleur de drill-down est rejetée, si l'utilisateur appuyait sur le bouton Enregistrer, que takeNewDate: méthode sera appelée avec la nouvelle valeur, et tout ce que vous avez à faire est bâton de la nouvelle date de retour dans votre modèle de données. La classe du contrôleur est autonome, et il n'y a aucun besoin de modifier la classe du contrôleur du tout (mais n'hésitez pas à étendre sur elle si vous voulez). Si vous souhaitez personnaliser l'apparence du sélecteur de date, vous pouvez utiliser la propriété DatePicker du contrôleur, par exemple, pour changer le mode le sélecteur de date de:

controller.datePicker.datePickerMode = UIDatePickerModeDateAndTime;

Voici la classe sélecteur de date:

DateViewController.h
/*
DateViewController.h
*/


#import <UIKit/UIKit.h>
#import "Person.h"

@protocol DateViewDelegate <NSObject>
@required
- (void)takeNewDate:(NSDate *)newDate;
- (UINavigationController *)navController; // Return the navigation controller
@end


@interface DateViewController : UIViewController {
UIDatePicker *datePicker;
NSDate *date;

id <DateViewDelegate> delegate; // weak ref
}
@property (nonatomic, retain) IBOutlet UIDatePicker *datePicker;
@property (nonatomic, retain) NSDate *date;
@property (nonatomic, assign) id <DateViewDelegate> delegate;
-(IBAction)dateChanged;
@end


DateViewController.m
/*
DateViewController.m
*/

#import "DateViewController.h"
#import "BirthdaysCategories.h"

@implementation DateViewController
@synthesize datePicker;
@synthesize date;
@synthesize delegate;

-(IBAction)dateChanged
{
self.date = [datePicker date];
}
-(IBAction)cancel
{
[[self.delegate navController] popViewControllerAnimated:YES];
}
-(IBAction)save
{
[self.delegate takeNewDate:date];
[[self.delegate navController] popViewControllerAnimated:YES];
}
- (void)loadView
{
UIView *theView = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
self.view = theView;
[theView release];


UIDatePicker *theDatePicker = [[UIDatePicker alloc] initWithFrame:CGRectMake(0.0, 206.0, 320.0, 216.0)];
self.datePicker = theDatePicker;
[theDatePicker release];
[datePicker addTarget:self action:@selector(dateChanged) forControlEvents:UIControlEventValueChanged];
[self.view addSubview:datePicker];


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:UIBarButtonItemStylePlain
target:self
action:@selector(save)]
;
self.navigationItem.rightBarButtonItem = saveButton;
[saveButton release];

self.view.backgroundColor = [UIColor groupTableViewBackgroundColor];

}

- (void)viewWillAppear:(BOOL)animated
{
if (self.date != nil)
[self.datePicker setDate:date animated:YES];
else
[self.datePicker setDate:[NSDate date] animated:YES];

[super viewWillAppear:animated];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void)dealloc {
[datePicker release];
[date release];
[super dealloc];
}
@end



Contrôleurs réutilisables

Je pensais prendre une pause de la substance OpenGL pour finir un post j'ai pensé à faire pendant un moment. Une idée fausse que beaucoup de nouveaux développeurs Cocoa Touch / cacao semblent avoir, c'est que vos classes contrôleur d'application doivent être complètement personnalisé. Il ya quelque fondement de cette croyance, comme chaque application aura besoin d'avoir certaines fonctionnalités qui sont spécifiques à lui-même, mais il ya un certain nombre de génériques, les classes de contrôleur réutilisables, tels que UITableViewController et UINavigationController qui gèrent certains ou tous les aspects impliqués dans la commande d'un certain type d'interface utilisateur.

Pourtant, beaucoup de personnes ne portent pas cette idée de réutilisation dans leur code propre contrôleur pour une raison quelconque. Trop souvent, vous voyez des projets avec les classes de contrôleur de plusieurs qui sont tous très semblables les uns aux autres. Un endroit que j'ai vu ce lot a est quand les gens en œuvre basée sur des tables de montage vues détails comme ceux utilisés dans l'application Contacts. Voici un exemple de ce dont je parle:

Je suis honnêtement surpris que Apple ne fournit pas une classe contrôleur générique pour ce scénario particulier, mais ils n'en ont pas. Il n'y a aucune raison pour laquelle nous ne pouvons pas créer notre propre classe générique modifiable contrôleur de détails volet.

Je vais donner le code pour une version que j'ai utilisé dans quelques projets. Il permet l'édition de cinq champs de texte. La seule raison pour cinq champs est pris en charge parce que c'est tout ce qui peut être affiché avec le clavier. Si vous avez besoin de plus de cinq champs, vous devriez probablement scinder en bas forage multiples.

Pour utiliser cette classe, vous créez le contrôleur et placez-vous en tant que délégué. Vous pouvez alors définir trois propriétés. Les trois tableaux représentent les champs à afficher, donc l'élément à l'index 0 dans les trois tableaux sont des données différentes sur le même domaine, comme ceci:
TextFieldEditingViewController *controller = [[TextFieldEditingViewController alloc] initWithStyle:UITableViewStyleGrouped];
controller.delegate = self;

controller.fieldNames = myArrayContainingTheLabelsToBeDisplayed;
controller.fieldKeys = myArrayContainingTheKeyValuesForTheItemToBeDisplayed;
controller.fieldValues = myArrayContainingTheCurrentValuesForTheItemsToBeDisplayed;

FieldNames doit contenir l'étiquette pour être utilisé par le contrôleur de détail pour chaque élément. Ceci est le texte en bleu dans la capture d'écran ci-dessus que l'utilisateur voit. Le fieldKeys est la clé qui correspond à chaque domaine. Ce sera généralement le nom de propriété pour le terrain en cours d'édition, et sera utilisé dans la méthode qui est utilisée pour transmettre des valeurs de retour au délégué. FieldValues ​​tiendra les valeurs actuelles de chacun des champs. Tous deux sans trois de ces propriétés doivent être définies, et elles doivent être NSArrays ou une sous-classe de celle-ci. Tous les trois doivent contenir le même nombre d'objets, et tous les trois doivent contenir cinq objets ou moins.

Il ya une autre propriété facultative que vous pouvez définir: keyboardTypes, qui est un tableau de cinq éléments UIKeyboardTypes. Ceci peut être utilisé pour indiquer au contrôleur de détail ce type de clavier pour montrer à l'utilisateur pour chaque champ qui peut être édité. Ces défaut à tous les UIKeyboardTypeAlphabet, mais si, par exemple, l'une des valeurs que vous souhaitez modifier le numéro de téléphone est, vous pouvez passer UIKeyboardTypePhonePad pour l'indice de tableau qui correspond à ce domaine.

Notez que dans la pseudo-code ci-dessus que nous avons mis l'auto en tant que délégué du contrôleur. Voilà comment nous en seront avisés si l'utilisateur éditée tous les champs. Le valuesDidChange: méthode sera appelée sur le délégué, en passant un dictionnaire en utilisant le codage clé-valeur qui informe le délégué de l'ensemble des modifications apportées si l'utilisateur appuyait sur le bouton Enregistrer. Le délégué est alors chargé de prendre les valeurs de ce tableau et les bourrant à l'endroit approprié.

Cette classe n'est pas aussi poli et n'a pas été testé à fond comme des classes d'Apple contrôleur générique, mais il a certainement réduit le nombre de classes de contrôleur dont j'ai besoin dans certains de ma table des applications basées sur. Alors, sans plus tarder, voici qu'elle est:

TextFieldEditingViewController.h
/*
TextFieldEditingViewController.h
*/


#import <UIKit/UIKit.h>
#define kDefaultLabelTag 50002

@protocol TextFieldEditingViewControllerDelegate <NSObject>
@required
- (void)valuesDidChange:(NSDictionary *)newValues;
- (UINavigationController *)navController; // Return the navigation controller
@end


@interface TextFieldEditingViewController : UITableViewController <UITextFieldDelegate> {

NSArray *fieldNames; // Field name to be displayed to user
NSArray *fieldKeys; // Key value to be used in dictionary when values are passed back to delegate
NSArray *fieldValues; // Starting display values for each field. Values should be strings.

NSMutableArray *changedValues; // Changes will be stored in this array , which will also be passed back to delegate on save
UIKeyboardType keyboardTypes[5]; // Keyboard types for each field

id <TextFieldEditingViewControllerDelegate> delegate; // Delegate who will received the changed values. Delegate
// is responsble for converting back from string if necessary

UITextField *textFieldBeingEdited; // The field currently being edited

UIBarButtonItem *oldLeftButton; // Used to restore old button values
UIBarButtonItem *oldRightButton;
}

@property (nonatomic, retain) NSArray *fieldNames;
@property (nonatomic, retain) NSArray *fieldKeys;
@property (nonatomic, retain) NSArray *fieldValues;
@property (nonatomic, retain) NSMutableArray *changedValues;
@property (nonatomic, assign /* for weak ref */) id <TextFieldEditingViewControllerDelegate> delegate;
@property (nonatomic, retain) UITextField *textFieldBeingEdited;
@property (nonatomic, retain) UIBarButtonItem *oldLeftButton;
@property (nonatomic, retain) UIBarButtonItem *oldRightButton;
-(IBAction)cancel;
-(IBAction)save;
-(IBAction)textFieldDone:(id)sender;
-(void)setKeyboardType:(UIKeyboardType)theType forIndex:(NSUInteger)index;
@end




TextFieldEditingViewController.m
/*
TextFieldEditingViewController.m

*/

#import "TextFieldEditingViewController.h"
#import "BirthdaysAppDelegate.h"

@implementation TextFieldEditingViewController
@synthesize fieldNames;
@synthesize fieldKeys;
@synthesize fieldValues;
@synthesize delegate;
@synthesize changedValues;
@synthesize textFieldBeingEdited;
@synthesize oldLeftButton;
@synthesize oldRightButton;
- (id)initWithStyle:(UITableViewStyle)style
{
if (self = [super initWithStyle:style])
{
for (int i =0; i < 5; i++)
keyboardTypes[i] = UIKeyboardTypeAlphabet;
}
return self;
}
-(IBAction)textFieldDone:(id)sender
{
UITableViewCell *cell = (UITableViewCell *)[[(UIView *)sender superview] superview];
UITableView *table = (UITableView *)[cell superview];
NSIndexPath *textFieldIndexPath = [table indexPathForCell:cell];
NSUInteger row = [textFieldIndexPath row];
row++;
if (row >= [fieldNames count])
row = 0;
NSUInteger newIndex[] = {0, row};
NSIndexPath *newPath = [[NSIndexPath alloc] initWithIndexes:newIndex length:2];
UITableViewCell *nextCell = [self.tableView cellForRowAtIndexPath:newPath];
UITextField *nextField = nil;
for (UIView *oneView in nextCell.contentView.subviews)
{
if ([oneView isMemberOfClass:[UITextField class]])
nextField = (UITextField *)oneView;
}
[nextField becomeFirstResponder];

}
- (void)viewWillAppear:(BOOL)animated
{
self.oldLeftButton = self.navigationItem.leftBarButtonItem;
self.oldRightButton = self.navigationItem.rightBarButtonItem;

UIBarButtonItem *saveButton = [[UIBarButtonItem alloc]
initWithTitle:@"Save"
style:UIBarButtonItemStylePlain
target:self
action:@selector(save)]
;
self.navigationItem.rightBarButtonItem = saveButton;
[saveButton release];

UIBarButtonItem *cancelButton = [[UIBarButtonItem alloc]
initWithTitle:@"Cancel"
style:UIBarButtonItemStylePlain
target:self
action:@selector(cancel)]
;
self.navigationItem.leftBarButtonItem = cancelButton;
[cancelButton release];

[super viewWillAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated {
self.navigationItem.leftBarButtonItem = oldLeftButton;
self.navigationItem.rightBarButtonItem = oldRightButton;
[super viewWillDisappear:animated];
}
-(IBAction)cancel
{
[[self.delegate navController] popViewControllerAnimated:YES];
}
-(IBAction)save
{
if (textFieldBeingEdited != nil)
[changedValues replaceObjectAtIndex:textFieldBeingEdited.tag withObject:textFieldBeingEdited.text];

[self.delegate valuesDidChange:[NSMutableDictionary dictionaryWithObjects:changedValues forKeys:fieldKeys]];
[[self.delegate navController] popViewControllerAnimated:YES];
}
-(void)setKeyboardType:(UIKeyboardType)theType forIndex:(NSUInteger)index
{
keyboardTypes[index] = theType;
}
#pragma mark -
- (void)setFieldNames:(NSArray *)theFieldNames
{
if ([theFieldNames count] > 5)
{
NSException *e = [NSException exceptionWithName:@"Too Many Values"
reason:@"If more than five values are provided, some will be inaccessible because of the keyboard view"
userInfo:nil
]
;
[e raise];
}
[theFieldNames retain];
[fieldNames release];
fieldNames = theFieldNames;
}
- (void)setFieldValues:(NSArray *)theFieldValues
{
[theFieldValues retain];
[fieldValues release];
fieldValues = theFieldValues;

changedValues = [theFieldValues mutableCopy];
}




- (void)dealloc {
[fieldNames release];
[fieldKeys release];
[fieldValues release];
[textFieldBeingEdited release];
[super dealloc];
}

#pragma mark -
#pragma mark Table View Data Source Methods
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [fieldNames count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *textFieldCellIdentifier = @"textFieldCellIdentifier";


UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:textFieldCellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:textFieldCellIdentifier] autorelease];
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 75, 25)];
label.textAlignment = UITextAlignmentRight;
label.tag = kDefaultLabelTag;
UIFont *font = [UIFont boldSystemFontOfSize:11];
label.textColor = [UIColor colorWithRed:0.4 green:0.4 blue:0.6 alpha:1.0];
label.font = font;
[cell.contentView addSubview:label];
[label release];


UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(94, 10, 200, 25)];
//textField.tag = kDefaultTextFieldTag;
textField.clearsOnBeginEditing = NO;
[textField setDelegate:self];
[textField addTarget:self
action:@selector(textFieldDone:)
forControlEvents:UIControlEventEditingDidEndOnExit
]
;
[cell.contentView addSubview:textField];
}
UILabel *label = (UILabel *)[cell.contentView viewWithTag:kDefaultLabelTag];
UITextField *textField = nil;
for (UIView *oneView in cell.contentView.subviews)
{
if ([oneView isMemberOfClass:[UITextField class]])
textField = (UITextField *)oneView;
}

label.text = [fieldNames objectAtIndex:[indexPath row]];
textField.text = [changedValues objectAtIndex:[indexPath row]];
textField.tag = [indexPath row];
textField.keyboardType = keyboardTypes[[indexPath row]];
return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}

#pragma mark -
#pragma mark Text Field Delegate Methods
#pragma mark -
#pragma mark Table Delegate Methods
- (NSIndexPath *)tableView:(UITableView *)tableView
willSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
return nil;
}
#pragma mark -
#pragma mark Text Field Delegate Methods
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
self.textFieldBeingEdited = textField;
}
- (void)textFieldDidEndEditing:(UITextField *)textField
{

[changedValues replaceObjectAtIndex:textField.tag withObject:textField.text];
}

@end