我正在尝试将 aUITextField
作为子视图添加到我的表格单元格中。文本字段的内容很好,直到我开始滚动并且单元格开始被重用。图片说明了问题。
起初,右边的蓝色值UITextField
是正确的,即该值对应于行号。向下和向上滚动的第二和第三张图像显示这些值正在以奇怪的方式被重用。
我该如何避免这种情况?使用唯一值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;
}