views:

32

answers:

2

I'm creating a form and was wondering if anyone knows how to retrieve a UITextField value from a table cell.

- (IBAction)saveForm:(id)sender {
   NSLog(@"TextField Value => %@", titleField.text);
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ...
switch(indexPath.section)
{
    case 0:
        if (row == 0) {
        cell.selectionStyle = UITableViewCellSelectionStyleNone;

        CGRect titleFieldFrame = CGRectMake(20.0, 80.0, 280.0, 25.0);
        UITextField *titleField = [[UITextField alloc] initWithFrame:titleFieldFrame];
        [titleField setBorderStyle:UITextBorderStyleRoundedRect];
        [titleField setTextColor:[UIColor blackColor]];
        [titleField setFont:[UIFont systemFontOfSize:16]];
        [titleField setPlaceholder:@"Title"];
        [titleField setBackgroundColor:[UIColor whiteColor]];
        titleField.keyboardType = UIKeyboardTypeDefault;
        titleField.returnKeyType = UIReturnKeyDone;
        [cell addSubview:titleField];
    } 
    break;    
return cell;

}

A: 

Give a special tag to the titleField, e.g.

    UITextField *titleField = [[UITextField alloc] initWithFrame:titleFieldFrame];
    titleField.tag = 11280492;

and then use -viewWithTag: to get that view.

-(IBAction)saveForm:(id)sender {
   UITableViewCell* cell = ...
   UITextField* titleField = [cell viewWithTag:11280492];
   NSLog(@"TextField Value => %@", titleField.text);
}
KennyTM
Hey KennyTM, I appreciate the help, and you have also helped me see other ways of using Tag. DarkDust answer seemed much simpler and also worked. Thanks.
KB
A: 

You could simply create an instance variable and assign titleField to that. Or you could assign a tag with [titleField setTag:123] and then later retrieve it via [yourTableView viewWithTag:123].

DarkDust
It worked. I didn't know about the setTag but I will research more about it and see how else it could be used. Thanks DarkDust.
KB