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?
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.
My suggestion is to not use custom UITableViewCell
s. 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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With