我有UITableView
个自定义UITableViewCells
,每个人都有一个UITextField
。我向每个textField分配一个值为indexPath.row + 100
的标记。
好吧,当我在特定的textField中键入内容时,我想更新每个单元格的每个textField。更清楚的是,当我键入一个数字时,我的viewcontroller应该进行一些计算,然后将结果分配给所有其他textFields,这必须在每次从textField修改文本时完成,假设我输入1(进行一些计算和将结果分配到textFields),然后我输入2,现在要计算的数字,将是12,依此类推。
问题是我可以从tableView重新加载数据而不关闭keyboar。系统将自动隐藏UIKeyboard,因此在这种情况下reloaddata不起作用。
我尝试使用NSMutableArray存储所有这些textFields,但是当从cellForRowAtIndexPath添加它们时它们会得到很多。
如何正确更新所有这些UITextFields
?
答案 0 :(得分:1)
它只需要更新可见单元格,但不能更新所有单元格。 假设内容计算公式非常简单:
-(NSString*) textForRowAtIndex:(int)rowIndex
{
return [NSString stringWithFormat:@"%d", startRowValue + rowIndex];
}
每个单元格都包含带有标记UITextField
的{{1}}对象:
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:
让我们有50个细胞:
-(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];
}
}
}
完成编辑后隐藏键盘:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return 50;
}
享受!