У меня есть гетерогенное табличное представление с целым разделом, состоящим из UITableViewCells, с элементом управления UITextField для каждого объекта contetView. Проблема в том, что при прокрутке текст, написанный в текстовых полях, смешивается.
Я уже много раз видел эту проблему, и хотя она устарела, я решил назначить разные ячейки для каждого типа ячейки.
Что отличается сейчас, так это то, что я создаю ячейки динамически, и в зависимости от ответа сервера раздел таблицы может иметь ноль или более пользовательских ячеек (та, которая имеет textField).
Теперь интересно видеть, что свойства текстового файла, такие как заполнитель, постоянны во всех свитках, но текст, который я пишу, вообще не является постоянным, текст меняет свою позицию ...
У меня есть видео здесь , чтобы вы могли понять, что я имею в виду.
Код, который я использую, выглядит следующим образом:
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
NSString *varCellID = [NSString stringWithFormat:@"%i_VarCellID", (indexPath.row + 7891)];
if (indexPath.section == 0) {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier] autorelease];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
[self configureCellViews:cell indexPath:indexPath];
}
[self configureCellContent:cell indexPath:indexPath];
return cell;
}
else if (indexPath.section == 1) {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier] autorelease];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
[self configureCellViews:cell indexPath:indexPath];
}
[self configureCellContent:cell indexPath:indexPath];
return cell;
}
else {
UITableViewCell *varCell = [tableView dequeueReusableCellWithIdentifier:varCellID];
if (varCell == nil) {
varCell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:varCellID] autorelease];
varCell.selectionStyle = UITableViewCellSelectionStyleNone;
[self configureCellViews:varCell indexPath:indexPath];
}
[self configureCellContent:varCell indexPath:indexPath];
return varCell;
}
}
Я знаю, что это не элегантно, но проснулся раньше. За исключением динамически созданного идентификатора ячейки, который является одной из моих (отчаянных) попыток сохранить индивидуальное содержимое в каждом текстовом поле.
Вот как я создаю представления и содержимое ячейки:
#pragma mark -
#pragma mark ConfigureCellcontent
- (void)configureCellViews:(UITableViewCell *)cell indexPath:(NSIndexPath *)indexPath {
NSArray *aSection = [sections objectAtIndex:indexPath.section];
NSDictionary *aField;
int varformatid;
if (indexPath.section == 0) {
cell.detailTextLabel.textAlignment = UITextAlignmentLeft;
}
else if (indexPath.section == 1) {
cell.detailTextLabel.textAlignment = UITextAlignmentLeft;
}
else {
aField = [aSection objectAtIndex:indexPath.row];
varformatid = [[aField valueForKey:@"varformatid"] intValue];
NSArray *aSection = [sections objectAtIndex:indexPath.section];
NSLog(@"format id %@", [[aSection objectAtIndex:0] valueForKey:@"varname"]);
fieldLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 7, 100, 30)];
fieldLabel.tag = 1234;
fieldLabel.textAlignment = UITextAlignmentLeft;
fieldLabel.font = [UIFont boldSystemFontOfSize:14];
fieldLabel.adjustsFontSizeToFitWidth = YES;
[cell.contentView addSubview:fieldLabel];
theTextField = [[UITextField alloc] initWithFrame:CGRectMake(130, 12, 170, 30)];
theTextField.textColor = kAnswersTextColor;
theTextField.returnKeyType = UIReturnKeyDone;
theTextField.tag = indexPath.row + 101;
theTextField.adjustsFontSizeToFitWidth = YES;
theTextField.delegate = self;
if(varformatid == 6 || varformatid == 7 || varformatid == 8) {
// use number pad input
theTextField.keyboardType = UIKeyboardTypeNumberPad;
[cell addSubview: theTextField];
[theTextField release];
}
else if(varformatid == 4) {
// use date
}
else if(varformatid == 17 || varformatid == 18) {
// use pull down, elements of pull down are in XML
}
else if(varformatid == 20) {
theSwitch = [[UISwitch alloc] initWithFrame:CGRectMake(120, 8, 100, 30)];
theSwitch.selected = YES;
[cell.contentView addSubview:theSwitch];
}
else {
// use input string
[cell addSubview: theTextField];
[theTextField release];
}
}
}
- (void)configureCellContent:(UITableViewCell *)cell indexPath:(NSIndexPath *)indexPath {
NSArray *aSection = [sections objectAtIndex:indexPath.section];
NSString *aField;
if (indexPath.section == 0) {
aField = [[aSection objectAtIndex:0] valueForKey:@"SetDate"];
cell.textLabel.text = @"Set Date";
cell.detailTextLabel.text = aField;
}
else if (indexPath.section == 1) {
aField = [[aSection objectAtIndex:0] valueForKey:@"SetType"];
cell.textLabel.text = @"Set Type";
cell.detailTextLabel.text = aField;
}
else {
aField = [[aSection objectAtIndex:indexPath.row] valueForKey:@"varname"];
if ([[[aSection objectAtIndex:indexPath.row] valueForKey:@"varrequired"] isEqualToString:@"yes"]) {
[(UITextField *)[cell viewWithTag:indexPath.row + 101] setPlaceholder: @"Required"];
}
else [(UITextField *)[cell viewWithTag:indexPath.row + 101] setPlaceholder: @"Optional"];
[(UILabel *)[cell.contentView viewWithTag:1234] setText: aField];
}
}
Наконец, я прошу вашей помощи найти хотя бы один лучший подход. Заранее спасибо.