它只需要更新可见单元格,而不是全部。假设内容计算公式非常简单:
-(NSString*) textForRowAtIndex:(int)rowIndex
{
return [NSString stringWithFormat:@"%d", startRowValue + rowIndex];
}
每个单元格都包含UITextField
带有标签的对象indexPath.row + 100
:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString* cellId = @"cellId";
UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:cellId];
if(!cell)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId] autorelease];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
UITextField* tf = [[[UITextField alloc] initWithFrame:CGRectMake(10, 8, 280, 30)] autorelease];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldTextDidChange:)
name:UITextFieldTextDidChangeNotification object:tf];
tf.delegate = (id)self;
[cell.contentView addSubview:tf];
}
UITextField* tf = (UITextField*)[[cell.contentView subviews] lastObject];
tf.tag = indexPath.row + 100;
tf.text = [self textForRowAtIndex:indexPath.row];
return cell;
}
然后所有可见单元格都将在textFieldTextDidChange:
方法中更新:
-(void) textFieldTextDidChange:(NSNotification*)notification
{
UITextField* editedTextField = (UITextField*)[notification object];
int editedRowIndex = editedTextField.tag - 100;
int editedValue = [editedTextField.text intValue];
startRowValue = editedValue - editedRowIndex;
for (NSIndexPath* indexPath in [self.tableView indexPathsForVisibleRows])
{
if(indexPath.row != editedRowIndex)
{
UITableViewCell* cell = [self.tableView cellForRowAtIndexPath:indexPath];
UITextField* textField = (UITextField*)[cell.contentView viewWithTag:indexPath.row+100];
textField.text = [self textForRowAtIndex:indexPath.row];
}
}
}
让我们有 50 个单元格:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return 50;
}
并在完成编辑时隐藏键盘:
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
[textField resignFirstResponder];
return YES;
}
享受!