Objective-C:获取每个 table 行的文本字段值

Objective-C: Get text field values of each table row

我有一个包含海关单元格的 table 视图。每个单元格都有两个文本字段。 table 下方是一个按钮。我在 table 视图控制器中有一个 "buttonPressed" 动作。如何在此方法中获取每个 table 行的文本字段值?

这是自定义单元格头文件:

...

@interface CustomCell : UITableViewCell
@property (weak, nonatomic) IBOutlet UITextField *name;
@property (weak, nonatomic) IBOutlet UITextField *age;

@end

在 table 视图控制器中我有这个方法:

- (IBAction)saveBtnPressed:(id)sender{
    // Store the text field values of each row in an array here
}

有人可以帮助我吗?

根据 ios 设计模式,您需要将文本字段的值存储在自定义单元格委托的数组中。但是对于您的示例,如果您希望所有文本字段值都位于同一位置,那么下面是适合您的解决方案。假设 saveBtnPressed 操作在 viewController 中(不在 Customcell 中)。假设有 5 行。

- (IBAction)saveBtnPressed:(id)sender{

       NSMutableArray *userDetails = [[NSMutableArray alloc] init];
       for(i=0;i<5;i++){
           CustomCell *cell = [tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0]];
           NSDictionary *userDictionary = [[NSDictionary alloc] initWithObjectsAndKeys: cell.name.text, @"name", cell.age.text, @"age", nil];
          [userDetails addObject:userDictionary];
       }
}

userDetailsArray 将包含所有单元格的详细信息。

尝试以下步骤:

cellForRowAtIndexPath 中为两个文本字段设置标签。

遍历数据源数组计数,这将与行数相同。

在循环中获取单元格,使用标签获取文本字段并将文本保存到字典数组:

- (IBAction)OnsaveCilck:(id)sender{

    NSMutableArray *Array = [NSMutableArray array];

    for (int i=0; i < YourDataSourceArray.Count; i++){ 

        NSIndexPath *indexPath = [NSIndexPath indexPathForRow: i inSection: 0];

        CustomCell *cell = [tableview cellForRowAtIndexPath:indexPath];

        NSMutableDictionary *Dict = [NSMutableDictionary dictionary];

        UITextField *TextName= (UITextField*)[cell.contentView viewWithTag:100];//tag given cellForRowAtIndexPath
        UITextField *TextAge= (UITextField*)[cell.contentView viewWithTag:200];//tag given cellForRowAtIndexPath

        [Dict setObject:TextName.text forKey:@"name"];
        [Dict setObject:TextAge.text forKey:@"age"];

        [Array addObject:TempDict];

    }

    //Final array contains all data

    NSLog(@"array == %@",Array);
}