OGeek|极客世界-中国程序员成长平台

标题: ios - 使用 UITableViewCell 附件 CheckMark [打印本页]

作者: 菜鸟教程小白    时间: 2022-10-23 05:24
标题: ios - 使用 UITableViewCell 附件 CheckMark

我正在努力完成这项工作,但似乎无法理解这个想法。

到目前为止,我已经有了它,你可以选择一个单元格,它可以产生一个复选标记。然后,当你选择一个不同的单元格时,之前的复选标记会消失,tableview 会在你刚刚选择的新单元格上做一个新的复选标记。这一切都很好。

但是,当您选择带有复选标记的相同单元格时,我想将其移至何处,
复选标记不会消失。但是,确实如此!

我已经尝试了大量的 if 语句,看看我是否能弄清楚如何完成这项工作,但找不到解决方案。这可能是我需要在代码中重新排列的小事。

这是我的代码:

- (void)tableViewUITableView *)tableView didSelectRowAtIndexPathNSIndexPath *)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);

    }
}



Best Answer-推荐答案


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

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)tableViewUITableView *)tableView didSelectRowAtIndexPathNSIndexPath *)indexPath {
    UITableViewCell* cellCheck = [tableView
                                    cellForRowAtIndexPath:indexPath];
    cellCheck.accessoryType = UITableViewCellAccessoryCheckmark;
}

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

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

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






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://jike.in/) Powered by Discuz! X3.4