views:

3979

answers:

4

I've set up a UITableView with several custom UITableViewCell's that have some UITextField's and UISwitch's (based on Settings.app). My question is, when a user clicks the Save button in the navigation bar, what's the beat way to access these text fields and switch controls to save their values?

+8  A: 

My suggestion is to not use custom UITableViewCells. I used to do it your way, but there's a much better way. Use the accessoryView property of the UITableViewCell, which you can assign an arbitrary view to, such as a UITextField or UISwitch. It shows up exactly as it would in the Settings application.

Then, when you need to access it, just use

NSString *text = ((UITextField *)cell.accessoryView).text;

However, you must be careful about setting up cells and accessing their values. If any cell goes offscreen, it will be removed and you will not be able to access the text field. What you want to do when setting up your cell is:

cell.accessoryView = nil;  //Make sure any old accessory view isn't there.
if (/*cell needs text field*/) {
    UITextField *textField = [[[UITextField alloc] initWithFrame:frame] autorelease];
    textField.text = savedValue;
    cell.accessoryView = textField;
    [textField addTarget:self action:@selector(textChanged:) forControlEvents:UIControlEventValueChanged];
}

...

- (void) textChanged:(UITextField *)source {
    self.savedValue = source.text;
}
Ed Marty
A: 

If you don't follow Ed's suggestion, you are probably best retaining your text view in the custom cell and adding a property to access the view.

Roger Nolan
A: 

You can also have your custom cells keep a reference to your higher-level view controller and send it notifications when the user updates values in them. Basically, copy the delegate pattern used by many library objects in UIKit.

zem
A: 

I appreciate this post.

Question with the code above: There is an if statement "if (cell needs text field)"...

What exactly would I be checking against, the answer is YES it does, so are we checking to see if the text field is already present on the cell and then avoiding the call to create a new one?

what would that look like?

newDeveloper