表视图中的复选框单元格:用户无法检查它

Ben*_*son 2 iphone checkbox cocoa-touch uitableview uikit

我需要帮助使用复选框单元格.我目前将该对象添加到tableview.它看起来不错,直到我尝试构建和运行程序,我无法选中复选框.我目前正在使用tableview,它显示项目运行时,每个项目都有一个复选框,因此我可以有多个选项.

我是xcode的新手,因为这个问题,我已经被困了一个星期.我试过谷歌但仍然没有运气.

任何片段,答案或解释都非常感谢.

mgr*_*rog 5

首先我们需要编辑这个方法:- (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];
}
Run Code Online (Sandbox Code Playgroud)

现在我们知道哪些单元格需要在它们旁边有一个复选标记,下一步是修改单元格的显示方式.- (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;
}
Run Code Online (Sandbox Code Playgroud)

如果我们不调用reloadData,则复选标记将不会显示,直到它出现在屏幕外并重新出现.由于重复使用单元格的方式,您需要每次都显式设置accessoryType.如果仅在选中单元格时设置样式,则在滚动时,可能不一定要检查的其他单元格将具有复选标记.希望这能让您大致了解如何使用复选标记.