【问题标题】:Toggle checkmark between cells with one cell checked by default在单元格之间切换复选标记,默认选中一个单元格
【发布时间】:2014-02-27 20:10:35
【问题描述】:

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

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

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

【问题讨论】:

    标签: ios objective-c uitableview toggle checkmark


    【解决方案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...

    【讨论】:

    • 添加后 self.checkedIndexPath = [NSIndexPath indexPathForRow:0 inSection:1];问题已经解决了。谢谢@大卫
    • 从我在这里看到的你可能想要 inSection:0,而不是 inSection:1,但我看不到你的整个应用程序 :)
    • 一个问题。当我在将 self.checkedIndexPath 设置为 [NSIndexPath indexPathForRow:0 inSection:1] 之前注销 self.checkedIndexPath 时,self.checkedIndexPath 为 0。但是如果我在将 self.checkedIndexPath 设置为 [NSIndexPath indexPathForRow:0 inSection 之后注销 self.checkedIndexPath :1],self.checkedIndexPath 为 -4611686018427387818。当我想根据我的 didSelectRowAtIndexPath 选择的索引路径设置不同的设置时,这会导致问题吗?
    • 确保将值记录为 NSLog(@"%@", self.checkedIndexPath) 在我看来,您现在正在使用其他格式打印它。
    猜你喜欢
    • 1970-01-01
    • 2021-08-24
    • 1970-01-01
    • 1970-01-01
    • 2013-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多