I have a UITableViewController that shows a list of items from NSMutableArray, along with a button that serves as a check box that the user can select/deselect. I am able to successfully display the table, as well as the checkboxes. However, I would like to have a tableheader at the very top of the table that would have a “select all” check box, which would allow the user to select all of the cells, or deselect all of the cells. If some cells are already checked off, then I want only those cells that are not selected, to be selected.
Here is the code that I have thus far:
- (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];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
testButton = [UIButton buttonWithType:UIButtonTypeCustom];
[testButton setFrame:CGRectMake(280, 57, 25, 25)];
[testButton setImage:[UIImage imageNamed:@"CheckBox1.png"] forState:UIControlStateSelected];
[testButton setImage:[UIImage imageNamed:@"CheckBox2.png"] forState:UIControlStateNormal];
[testButton setUserInteractionEnabled:YES];
[testButton addTarget:self action:@selector(buttonTouched:) forControlEvents:UIControlEventTouchUpInside];
[cell setAccessoryView:testButton];
}
// Configure the cell...
TestObject *tObject = [[DataModel sharedInstance].testList objectAtIndex:indexPath.row];
cell.textLabel.text = tObject.testTitle;
return cell;
}
-(void)buttonTouched:(id)sender
{
UIButton *btn = (UIButton *)sender;
if( [[btn imageForState:UIControlStateNormal] isEqual:[UIImage imageNamed:@"CheckBox1.png"]])
{
[btn setImage:[UIImage imageNamed:@"CheckBox2.png"] forState:UIControlStateNormal];
// other statements
}
else
{
[btn setImage:[UIImage imageNamed:@"CheckBox1.png"] forState:UIControlStateNormal];
// other statements
}
}
//Here is the additional method that I have added to my code to select all
-(void)clickOnCheckButton {
NSLog(@"Did it select?");
for (int i = 0; i < [self.tableView numberOfSections]; i++) {
for (int j = 0; j < [self.tableView numberOfRowsInSection:i]; j++) {
NSUInteger ints[2] = {i,j};
NSIndexPath *indexPath = [NSIndexPath indexPathWithIndexes:ints length:2];
UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
//Here is your code
[self buttonTouched:nil];
}
}
}
Does anyone have any suggestions on how to do this?
Thanks in advance to all who reply.
Take another
NSMUtableArrayas SelectedArrayin
didselectRowAtIndexPathrow You can Add remove objects fromSelectedArray.You can select a cell calling table view’s
selectRowAtIndexPathmethod:Put
for loopforselectedArrayto putcheckbutton only in selected cells.in Your CellForRow Method Use this
you can select All row and All Section by below method.