Tutorial :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?


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


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.


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.

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »