4thSpace
4thSpace

Reputation: 44352

Retrieving cells in UITableView

I have a UITableView that once a cell is clicked, it pushes tableViewB, which contains customcells. These cells contain TextFields. Once the user does any updating, they click "Save", which then pops tableViewB and goes to the first UITableView. I would like to get all of the UITextField values from tableViewB when Save is clicked. What is the best way to go about doing that?

The problem is that I need to loop through all UITableView cells. I'm not sure how that is done or if it is even a good approach. Just looking for help on what is a good technique here.

Upvotes: 1

Views: 1081

Answers (3)

Ed Marty
Ed Marty

Reputation: 39700

in your tableViewB header, declare:

NSMutableArray *stringArray;

and in the implementation:

- (id) init {  //whatever your tableViewB initializer looks like
    if ([self = [super init]) {
        //oldData is an NSArray containing the initial values for each text field in order
        stringArray = [[NSMutableArray alloc] initWithArray:oldData];
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ...
    //Making the cell
    [cell.textfield addTarget:self action:@selector(updateField:) forControlEvents:UIControlEventValueChanged];
    ....

    //Setting up the cell
    cell.textfield.tag = indexPath.row;
    cell.textfield.text = [stringArray objectAtIndex:indexPath.row];
    return cell;
}

- (void) updateField:(UITextField *)source {
    NSString *text = source.text;
    [stringArray replaceObjectAtIndex:source.tag withObject:text];
}

- (void) dealloc {
    [stringArray release];
}

There are several ways you can choose to get your data back to the original table view, either by delegate, or by having the stringArray declared as a variable passed in to the tableViewB initializer rather than allocated there.

Upvotes: 3

MrMage
MrMage

Reputation: 7496

You should be aware that, in general, there are only about as many cell allocated as displayed on the screen. The cells that are not visible are actually not persistent but only get created when tableView:cellForRowAtIndexPath: is called. I suggest you create an array to cache the contents of all the text fields and which gets updated whenever a user leaves a text field (e.g. the textField:shouldEndEditing: method or something like that) is called.

Upvotes: 3

parkman47
parkman47

Reputation: 38

If I understand your question - id each cell numerically and reference them in an array/climb the array to loop through them

Upvotes: 1

Related Questions