我有一个带有单元格的表,每个单元格中都有一个UITextField。我将这些textfields的委托设置为self,并在编辑结束后进行一些计算。
我的问题是textfields,每当我输入第一个字段以外的字段时,除了第一个字段之外,我的所有textfields都会被更新。当我输入第一个时,其他的都会很完美地更新。
这让我检查更新了哪些数据,尽管我将cell.textLabel.text设置为数组中的特定位置,但它没有显示该位置的值。
下面是我的cellForRowAtIndex方法:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
UITextField *tf;
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
cell.accessoryType = UITableViewCellAccessoryNone;
cell.selectionStyle = UITableViewCellSelectionStyleNone;
tf = [[UITextField alloc] initWithFrame:CGRectMake(self.view.frame.size.width/2 + 25,
5,
cell.contentView.frame.size.width/2 - 25 - 25,
cell.contentView.frame.size.height - 10)];
tf.font = [UIFont fontWithName:@"Helvetica" size:16];
tf.textAlignment = NSTextAlignmentLeft;
tf.backgroundColor = [UIColor clearColor];
tf.textColor = [UIColor blueColor];
tf.tag = indexPath.row;
tf.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
tf.returnKeyType = UIReturnKeyDone;
tf.delegate = self;
tf.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
cell.textLabel.text = [_titles objectAtIndex:indexPath.row];
tf.placeholder = cell.textLabel.text;
[cell.contentView addSubview:tf];
}
else
{
tf = (UITextField *)[cell viewWithTag:indexPath.row];
}
tf.text = [NSString stringWithFormat:@"%.2f", [[_data objectAtIndex:indexPath.row] floatValue]];
NSLog(@"Value at index %i is %.2f", indexPath.row, [[_data objectAtIndex:indexPath.row] floatValue]);
cell.textLabel.text = [_titles objectAtIndex:indexPath.row];
return cell;
}当我尝试这个时,经过我的计算,这是记录的内容:
在索引0处的值为1.20 索引1处的值为1.00。 指数2处的值为4.55
然而,第一个文本字段仍然显示为0,而不是1.20
我在添加这些文本框时出了什么问题?
发布于 2013-01-12 18:17:33
每次你创建文本字段并把它放在同一个地方.所以你的新的文本框是在previoulsy创建的后面创建的。
你需要检查这份声明
UITextField *tf;
和
tf = [[UITextField alloc] initWithFrame:CGRectMake(self.view.frame.size.width/2 + 25, 5,
cell.contentView.frame.size.width/2 - 25 - 25,
cell.contentView.frame.size.height - 10)];只有在上一次不存在的情况下,alloc+init才会出现。类似于您为cell所做的工作。
编辑
检查一下标签。如果我没有弄错,默认标记是0,因此当使用viewWithTag时,它可能选择textLabel而不是textfield。将textfield的标记设置为indexPath.row + 5。
发布于 2013-01-12 18:19:38
这一行代码看起来很糟糕:
tf = (UITextField *)[cell viewWithTag:indexPath.row];因为如果要重用TableViewCell,则行将不匹配。
例如,单元格被创建为第0行,并在第10行得到重用。因此,tf将为零,不会更新。
每个单元格都是自己的小生态系统,因此您不需要在每个单元格中为文本字段添加不同的标记。可能是tf.tag = SOME_CONSTANT;
另外,我假设您要求表视图重新加载它的数据。
https://stackoverflow.com/questions/14296384
复制相似问题