Reputation: 1103
I have a table view with customs cells. Each cell got two text fields. Below the table is a button. I have a "buttonPressed" action in the table view controller. How can I get the text field values of each table row in this method?
Here is the custom cell header file:
...
@interface CustomCell : UITableViewCell
@property (weak, nonatomic) IBOutlet UITextField *name;
@property (weak, nonatomic) IBOutlet UITextField *age;
@end
And in the table view controller I have this method:
- (IBAction)saveBtnPressed:(id)sender{
// Store the text field values of each row in an array here
}
Can someone help me?
Upvotes: 2
Views: 4179
Reputation: 2285
According to ios design pattern you need to store value of textfield in array in delegate of custom cell. But for your example if you want all textfield value as same place then below is solution for you. Assuming that saveBtnPressed action is in viewController(not in Customcell). Assuming there are 5 rows.
- (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 will have details of all cells.
Upvotes: 6
Reputation: 5435
Try below steps:
Set tag in cellForRowAtIndexPath
for both textField.
Loop through dataSource array count, which will be same as Number of Row.
Get cell in Loop, get textFields using tag and save text to array of dictionary:
- (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);
}
Upvotes: 1