user3126921
user3126921

Reputation: 23

How to reference a textfield's text in a UITableView's cell

I am very confused as to how to reference a textfield's text in a UITableView. I have 5 rows in a tableview which are loaded without text, the user inputs text which is then saved as settings. I am trying to have the arrays _textBox1Contents and _textBox2Contents contain the user-inputted text in the 5 textBox1 and textBox2 textfields. How do I reference the specific cell's textfields in order to send them using NSUserDefaults to other parts of the app?

Thanks in advance.

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"TableCell";
    TableCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

    // Configure the cell...

    long row = [indexPath row];

    cell.image.image = [UIImage imageNamed:_image[row]];
    cell.titleLabel.text = _Title[row];
    cell.textbox1.placeholder = _textBox1[row];
    cell.textbox2.placeholder = _textBox2[row];
    cell.colon.text = _colon[row];

    cell.textbox1.delegate = self;
    cell.textbox2.delegate = self;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;

    _textBox1Contents = @[@"",
                          @"",
                          @"",
                          @"",
                          @"",];

    _textBox2Contents = @[@"",
                          @"",
                          @"",
                          @"",
                          @"",];

    return cell;
}

Upvotes: 1

Views: 185

Answers (2)

Yurii Romanchenko
Yurii Romanchenko

Reputation: 848

You can add 'save' button for example and implement corresponding callback as :

- (IBAction)saveClicked:(id)sender {
    for (int i = 0; i < _tableView.numberOfSections; i++) {
        for (int j = 0; j < [_tableView numberOfRowsInSection:i]; j++) {
            NSIndexPath *currentIndexPath = [NSIndexPath indexPathForRow:j inSection:i];
            TableCell *currentCell = (TableCell *)[_tableView cellForRowAtIndexPath:currentIndexPath];
            // Get text field and store.
        }
    }

Upvotes: 1

Astri
Astri

Reputation: 575

Give a tag (lets say 100) on your UITextField. Then, on your cellForRowAtIndexPath do

UITextField *textField = (UITextField *)[cell viewWithTag:100];
textField.text = [NSString stringWithFormat:@"%d",indexPath.row];

Upvotes: 1

Related Questions