1

我的应用程序中有一个设置视图,我希望用户能够在一些不同的设置之间进行检查,但只允许用户当时选择其中一个选项。

我在这个答案中得到了一些帮助:iPhone:UITableView CellAccessory Checkmark

但是当我默认检查第一个单元格时,我无法让它正确切换。

这是在我的cellForRowAtIndexPath

if (indexPath.row == 0)
{
     // Set the first cell checked by default
     cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
else if([self.checkedIndexPath isEqual:indexPath])
{
     cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
else
{
     cell.accessoryType = UITableViewCellAccessoryNone;
}

这是我的didSelectRowAtIndexPath

// Uncheck the previous checked row
if(self.checkedIndexPath)
{
    UITableViewCell* uncheckCell = [tableView cellForRowAtIndexPath:self.checkedIndexPath];
    uncheckCell.accessoryType = UITableViewCellAccessoryNone;
}

UITableViewCell* cell = [tableView cellForRowAtIndexPath:indexPath];
cell.accessoryType = UITableViewCellAccessoryCheckmark;
self.checkedIndexPath = indexPath;

 [tableView deselectRowAtIndexPath:indexPath animated:YES];

默认情况下会检查该单元格,但是在检查另一个单元格时,仍然会检查第一个单元格,直到我再次检查它,然后检查另一个单元格,然后行为是正确的。

4

1 回答 1

1
if (!self.checkedIndexPath && indexPath.row == 0)
{
     // save away what cell is already checked
     self.checkedIndexPath = indexPath;

     // Set the first cell checked by default
     cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
...

或者: if(!self.checkedIndexPath) self.checkedIndexPath = indexPath;

if([self.checkedIndexPath isEqual:indexPath])
{
    ...
}
else
{
    ...
}

在您的 viewDidLoad 中交替添加 self.checkedIndexPath = [NSIndexPath indexPath forRow:0 inSection:0];

然后只需在您的 cellFor 中检查 checkedIndexPath = indexPath ...

于 2014-02-27T20:16:59.130 回答