ios - 在默认选中一个单元格的单元格之间切换复选标记

标签 ios objective-c uitableview toggle checkmark

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

我在整个回答过程中得到了一些帮助: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];

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

最佳答案

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];

然后让 checkedIndexPath = indexPath 检查你的 cellFor...

关于ios - 在默认选中一个单元格的单元格之间切换复选标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22079278/

相关文章:

ios - 如何在 CoreData 中匹配 NSSet 的对象值?

ios - UINavigationController 仅隐藏导航栏 - 后退动画问题

ios - Swift ios7 Storyboard - 自己启动主场景

objective-c - 调用 initWithNibName 时 "The result of a delegate init call must be immediately returned or assigned to ' self '"

ios - 如何从多个 Realm 模型创建一个 tableview?

iphone - 自定义 UITableViewCell 创建两次......让我发疯

iphone - UILabel 值不会在 cellForRowAtIndexPath 中更新?

iphone - UINavigationBar问题

ios - 删除 Realm 默认路径

iphone - 排序NSMutableDictionary的数据