从UITableView中删除行时删除UITextField内容

时间:2013-12-09 03:03:38

标签: ios objective-c uitableview uitextfield

我的应用程序中有一个包含6行的Player视图,Player One到Player Six。用户输入玩家名称并可以通过滑动和点击“删除”来删除行。当行的文本字段中有文本时,我遇到了问题。例如,我将前三行的文本字段填入'One'到'Three'。如果删除显示为“三”的第3行,它将删除该行,但文本字段中的文本“三”将进入播放器四下面的行。解决这个问题的最佳方法是什么?

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"playerCell";
    playerCell *cell = [tableView
                            dequeueReusableCellWithIdentifier:CellIdentifier
                            forIndexPath:indexPath];

    cell.playerLabel.text = [[_playerNames objectAtIndex:indexPath.row]objectForKey:@"title"];
    NSString *test = [NSString stringWithFormat:@"%@", cell.playerNameBox.text];
    cell.playerNameBox.tag = indexPath.row;

    NSString *key = [NSString stringWithFormat:@"%ld", (long)indexPath.row];
    [[NSUserDefaults standardUserDefaults]
     setObject:test forKey:key];

    return cell;
}

删除行:

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete)
    {
        [_playerNames removeObjectAtIndex:indexPath.row];
        [Table reloadData];

    }
}

section = 6

中的行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    return _playerNames.count;
}

1 个答案:

答案 0 :(得分:1)

在“cellForRowAtIndexPath”方法中,您没有正确检查零对象案例。

而不是:

cell.playerLabel.text = [[_playerNames objectAtIndex:indexPath.row]objectForKey:@"title"];

执行:

NSString *title = [[_playerNames objectAtInex:indexPath.row] objectForKey:@"title];
cell.playerLabel.text = (title ? title : @""); // set the label to either title or the empty string

我怀疑发生的事情是您在重新加载或重复使用时未正确重置文本标签。

但无论如何,为什么不是非常酷,而是删除标记为删除的行,而不是重新加载数据。

即:

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete)
    {
        [_playerNames removeObjectAtIndex:indexPath.row];
        [tableView deleteRowsAtIndexPaths: [NSArray arrayWithObject: indexPath] withRowAnimation: UITableViewRowAnimationLeft]; 
    }
}

另一个FYI:

我注意到你有:

    [Table reloadData];
你的代码中的

。 Objective-C的最佳实践是 用大写字母命名实例变量。它应该是更具描述性的内容,例如“itemTable”。