Tableview与复选框

PJR*_*PJR 2 iphone checkbox uitableview

我正在使用此代码与tableview复选框.

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

    cell.accessoryType = UITableViewCellAccessoryNone;

            cell.textLabel.text =@"a";
            int flag = (1 << indexPath.row);
            if (_checkboxSelections & flag) 
            {
                cell.accessoryType = UITableViewCellAccessoryCheckmark;
            }


    return cell;
}



#pragma mark -
#pragma mark Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
               _checkboxSelections ^= (1 << indexPath.row);
    [tableView reloadData];
}

- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 10;
}
Run Code Online (Sandbox Code Playgroud)

当我点击某个按钮时,我怎么知道选择了哪些单元格?

Emp*_*ack 5

您可以使用以下方法访问按钮操作上的tableView单元格.您可以使用if(cell.accessoryType == UITableViewCellAccessoryCheckmark)条件检查选择,因为您正在为所选单元格设置UITableViewCellAccessoryCheckmark.

- (void)onButtonClick {

    int numberOfSections = [tableView numberOfSections];

    for (int section = 0; section < numberOfSections; section++) {

        int numberOfRows = [tableView numberOfRowsInSection:section];

        for (int row = 0; row < numberOfRows; row++) {

            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:row inSection:section];
            UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];

            if (cell.accessoryType == UITableViewCellAccessoryCheckmark) {

                // Cell is selected

            } else {

                // Cell is not selected
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)