Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iPhone Table View: How to access text field of custom TableViewCell

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?

like image 798
Gilean Avatar asked Jun 07 '09 19:06

Gilean


People also ask

What is a prototype cell in iOS?

A prototype cell acts a template for your cell's appearance. It includes the views you want to display and their arrangement within the content area of the cell. At runtime, the table's data source object creates actual cells from the prototypes and configures them with your app's data.


1 Answers

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;
}
like image 198
Ed Marty Avatar answered Sep 26 '22 08:09

Ed Marty