Checkbox cell in table view: user cannot check this

I need help using a checkbox cell. I added an object to the tableview. It looks ok until I tried to build and run the program where I can't check the box. I am currently using a tableview that displays progress items with a checkbox for each item, so I can have multiple options.

I'm new to xcode and I've been stuck for a week with this problem. i tried google but still no luck.

Any snippets, answers or explanations are greatly appreciated.

+2


source to share


1 answer


First, we need to edit this method: - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

. Assuming you've created a navigation based app, this method should already be there, just commented out. I don't know the exact details of your implementation, but you somehow need to keep track of the checkbox state for every cell in the tableView. For example, if you have a BOOL array, the following code will work:

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

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

 [self.tableView reloadData];
}

      

Now that we know which cells should have a checkmark next to them, the next step is to change how the cell is displayed. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

processes the drawing of each cell. After creating the previous example, you will see a checkbox:



- (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;
}

      

If we do not call reloadData, the checkmark will not be displayed until it disappears and reappears. You need to explicitly specify the accessoriesType attribute each time due to the way cells are reused. If you set the style only when checking a cell, other cells that may not necessarily be checked will have a checkmark when scrolling. Hopefully this will give you a general idea of ​​how to use checkmarks.

+5


source







All Articles