Ячейки можно использовать повторно, поэтому им нужен более настойчивый способ хранения информации.
Метод 1:
Вы можете хранить несколько UITextField
объектов в массиве, если вы не хотите повторно использовать текстовые поля, а на cellForRowAtIndexPath
вам нужно всего лишь установить текстовые поля в их ячейках, например:
cell.txt1 = [textFieldsArray objectAtindex:indexPath.section*2];
cell.txt2 = [textFieldsArray objectAtindex:indexPath.section*2+1]; //txt1 and txt2 properties should have assign
Метод 2 :
Если вы также хотите повторно использовать текстовые поля, я предлагаю использовать массив с изменяемыми словарями, каждый словарь содержит «настройки» для ячейки. Текстовые поля будут полностью управляться пользовательской ячейкой (например, при значениях UIControlEventValueChanged
update update @ "txt1" или @ "txt2" из словаря, присоединенного к ячейке).
///somewhere in the initialization (in the class holding the tableview)
contentArray = [[NSMutableArray alloc] init];
///when adding a new cell (e.g: inside the 'Add set' action)
[contentArray addObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:@"", @"txt1", @"", @"txt2", nil]];
//add a new cell to the table (the same way you do now when tapping 'Add set')
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
...
[cell attachDictionary:[contentArray objectAtIndex:indexPath.section]];
return cell;
}
///anywhere where you'd like to access the values inserted inside a cell
NSMutableDictionary *cell3Content = [contentArray objectAtIndex:3];
NSString *text1 = [cell3Content valueForKey:@"txt1"];
NSString *text2 = [cell3Content valueForKey:@"txt2"];
///CustomCell.m
-(id)initWithCoder:(NSCoder *)decoder{
self = [super initWithCoder:decoder];
if(!self) return nil;
[txt1 addTarget:self action:@selector(txt1Changed:) forControlEvents:UIControlEventValueChanged];
[txt2 addTarget:self action:@selector(txt2Changed:) forControlEvents:UIControlEventValueChanged];
return self;
}
-(void)attachDictionary:(NSMutableDictionary *)dic{
contentDictionary = dic;
txt1.text = [contentDictionary valueForKey:@"txt1"];
txt2.text = [contentDictionary valueForKey:@"txt2"];
}
-(void)txt1Changed:(UITextField *)sender{
[contentDictionary setValue:txt1.text forKey:@"txt1"];
}