1

我想做一个典型的情况:当用户选择任何单元格时,它的附件类型会变成复选标记。只能对一个单元格的附件类型进行复选。然后我想保存在 NSUserDefaults indexPath.row 中,这样我的应用程序就能够知道选择了哪个单元格用户并对选项进行一些更改。所以我写了这个错误的代码:

didSelectRowAtIndexPath

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // checkedIndexPath is NSIndexPath

    if(self.checkedIndexPath)
    {
        UITableViewCell* uncheckCell = [tableView
                                        cellForRowAtIndexPath:self.checkedIndexPath];
        uncheckCell.accessoryType = UITableViewCellAccessoryNone;
    }
    UITableViewCell* cell = [tableView cellForRowAtIndexPath:indexPath];
    cell.accessoryType = UITableViewCellAccessoryCheckmark;

    self.checkedIndexPath = indexPath;

    [[NSUserDefaults standardUserDefaults]setObject:[NSNumber numberWithInt:self.checkedIndexPath.row]forKey:@"indexpathrow" ];
} 

cellForRowAtIndexPath

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Part of code from cellForRowAtIndexPath

    if(indexPath.row == [[[NSUserDefaults standardUserDefaults]objectForKey:@"indexpathrow"]intValue ])
    {
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
    }
    else 
    {
        cell.accessoryType = UITableViewCellAccessoryNone;
    }

        return cell;
}

但是,此代码效果不佳。当您打开时UITableView,表格中有一个已选择的单元格,当您按下另一个单元格时,有两个checkmarked单元格......我该如何改进我的代码还是应该将其全部更改?有什么建议么 ?谢谢 !

4

1 回答 1

6

试试这个代码:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // checkedIndexPath is NSIndexPath
    NSIndexPath *previousSelection = self.checkedIndexPath;
    NSArray *array = nil;
    if (nil != previousSelection) {
        array = [NSArray arrayWithObjects:previousSelection, indexPath, nil];
    } else {
        array = [NSArray arrayWithObject:indexPath];
    }

    self.checkedIndexPath = indexPath;

    [tableView reloadRowsAtIndexPaths:array withRowAnimation: UITableViewRowAnimationNone];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Part of code from cellForRowAtIndexPath
    NSString *cellID = @"CellID";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (nil == cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
        [cell autorelease];
    }

// some code for initializing cell content
    cell.selectionStyle = UITableViewCellSelectionStyleNone;

    if(self.checkedIndexPath != nil && indexPath.row == self.checkedIndexPath.row)
    {
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
    } else {
        cell.accessoryType = UITableViewCellAccessoryNone;
    }

    return cell;
} 
于 2012-05-16T16:00:46.040 回答