ios - 使用 UITableViewCellAccessoryCheckMark

标签 ios xcode uitableview checkmark

我正在尝试完成这项工作,但我似乎无法全神贯注于这个想法。

到目前为止,我已经知道您可以在其中选择一个单元格并生成复选标记。然后,当您选择一个不同的单元格时,先前的复选标记将消失,并且 tableview 将在您刚刚选择的新单元格上创建一个新的复选标记。这一切都很好。

但是,当您选择带有复选标记的同一个单元格时,我想把它转到哪里, 复选标记不会消失。但是,确实如此!

我已经尝试了大量的 if 语句来查看我是否可以弄清楚如何使它工作但无法找到解决方案。我需要在我的代码中重新安排这可能是一些小事。

这是我的代码:

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

    if(self.checkedIndexPath)
    {
        UITableViewCell* uncheckCell = [tableView
                                        cellForRowAtIndexPath:self.checkedIndexPath];
        uncheckCell.accessoryType = UITableViewCellAccessoryNone;
        [tableView deselectRowAtIndexPath:indexPath animated:YES];

    }

    if([self.checkedIndexPath isEqual:indexPath])
    {
        self.checkedIndexPath = nil;
    }

    else
    {
         cellCheck = [tableView cellForRowAtIndexPath:indexPath];
        cellCheck.accessoryType = UITableViewCellAccessoryCheckmark;
        self.checkedIndexPath = indexPath;
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
        NSLog(@"%@", indexPath);

    }
}

最佳答案

如果您选择带有复选标记的单元格,将执行此代码。

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

此代码将删除您在第一次选择期间添加的复选标记。

然后这段代码就会被执行

if([self.checkedIndexPath isEqual:indexPath])
{
    self.checkedIndexPath = nil;
}

因此只有当您再次选择同一个单元格时,复选标记才会重新出现

我认为更简洁的方法如下。

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell* cellCheck = [tableView
                                    cellForRowAtIndexPath:indexPath];
    cellCheck.accessoryType = UITableViewCellAccessoryCheckmark;
}

- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell* uncheckCell = [tableView
                                    cellForRowAtIndexPath:indexPath];
    uncheckCell.accessoryType = UITableViewCellAccessoryNone;
 }

因为您可以从 [tableView indexPathForSelectedRow] 获取 self.checkedIndexPath 的值; self.checkedIndexPath 的设置是可选的,具体取决于代码的逻辑。

关于ios - 使用 UITableViewCellAccessoryCheckMark,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13214471/

相关文章:

objective-c - DSBezelActivityView 上的内存泄漏

ios - 延迟后取消完成 block

c++ - Apple Mach-O 链接器错误,由于文件扩展名

iOS/xcode/objective-c : create session variable for reachability

ios - 如何将 UITextField 连接到 UITableView?

ios - 通过应用内购买解锁完整版本的安全方式

ios - 将纵向视频导出为正方形但具有 scaleAspectFit 比率

iphone - 查找不区分大小写的相似字符串 - iPhone

ios - UIImage 在 int 数组中获取图像的像素

ios - 匹配设计的 UITableViewCell 功能