UITextField
表のセルにサブビューとして aを追加しようとしています。スクロールを開始してセルが再利用されるまで、テキスト フィールドの内容は問題ありません。画像は問題を示しています。
最初は、右側の青い値UITextField
が正しいです。つまり、値は行番号に対応しています。下にスクロールして上に戻る 2 番目と 3 番目の画像は、値が奇妙な方法で再利用されていることを示しています。
どうすればこれを回避できますか? に一意の値を使用するとreuseIdentifier
この問題は解決しますが、明らかにあまり効率的ではありません。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITextField *numberTextField;
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
numberTextField = [[UITextField alloc] initWithFrame:CGRectMake(200, 10, 95, 30)];
numberTextField.adjustsFontSizeToFitWidth = YES;
numberTextField.textColor = [UIColor blueColor];
numberTextField.placeholder = @"Enter value";
numberTextField.keyboardType = UIKeyboardTypeDecimalPad;
numberTextField.tag = ([indexPath row]+1);
numberTextField.backgroundColor = [cell backgroundColor];
numberTextField.textAlignment = NSTextAlignmentRight;
numberTextField.clearButtonMode = UITextFieldViewModeNever;
numberTextField.clearsOnBeginEditing = YES;
[numberTextField setEnabled:YES];
[cell addSubview:numberTextField];
} else {
numberTextField = (UITextField *)[cell.contentView viewWithTag:([indexPath row]+1)];
}
cell.textLabel.text = [NSString stringWithFormat:@"Row %i",[indexPath row]+1];
numberTextField.text = [NSString stringWithFormat:@"Value: %i",[indexPath row]+1];
return cell;
}