在表视图复选框单元格:用户无法检查(Checkbox cell in a table view: U

2019-08-19 01:27发布

我需要使用复选框细胞帮助。 我现在添加的对象来实现代码如下。 它看起来不错,直到我试图建立和运行的程序,我不能选中复选框。 我目前使用的显示项目运行时对每个项目一个复选框,这样我就可以有多项选择的tableview。

我是新来的Xcode和我一直坚持了一个星期这个问题。 我试图谷歌,但仍然没有运气。

任何片段,答案或解释是非常赞赏。

Answer 1:

首先,我们需要修改这个方法: - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 。 假设你生成一个基于导航的应用程序,这种方法应该已经在那里了,只是注释掉。 我不知道你的实现的具体细节,但不知何故,你必须保持跟踪复选框的状态在的tableView每个单元格。 举例来说,如果你有一个BOOL数组,下面的代码将工作:

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

 if (checkboxArray[indexPath.row])
  checkboxArray[indexPath.row] = NO;
 else 
  checkboxArray[indexPath.row] = YES;

 [self.tableView reloadData];
}

现在我们知道了细胞需要旁边有一个对号,下一步是要修改单元格的显示方式。 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath处理每个小区的图。 建立关前面的例子,这是你将如何显示的复选框:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }

 if (checkboxArray[indexPath.row]) {
  cell.accessoryType = UITableViewCellAccessoryCheckmark;
 }
 else
  cell.accessoryType = UITableViewCellAccessoryNone;

 // Configure the cell.

    return cell;
}

如果我们不叫reloadData,复选标记不会显示出来,直到它熄灭屏幕和重新出现。 你需要每次都明确设置accessoryType的,因为细胞被再利用的方式。 如果您设置的样式只有当细胞被选中,其他可能不一定检查将有一个对号,当你去滚动细胞。 但愿这给你如何使用对号一个总体思路。



文章来源: Checkbox cell in a table view: User can't check it