UITableViewCellAccessoryCheckmark的逻辑

时间:2012-05-16 15:49:07

标签: iphone objective-c ios xcode uitableview

我想做一个典型的情况:当用户选择任何一个单元格时,它的accessoryType会以复选标记打开。只有一个单元格的accessoryType可以是复选标记。然后我想保存在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单元格...如何改进我的代码或者我应该更改它?有什么建议 ? 谢谢!

1 个答案:

答案 0 :(得分: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;
}