我有一个 UITableViewController,它显示 NSMutableArray 中的项目列表,以及一个用作用户可以选择/取消选择的复选框的按钮。我能够成功显示表格以及复选框。但是,我想在表格的最顶部有一个表头,它有一个“全选”复选框,允许用户选择所有单元格,或取消选择所有单元格。如果某些单元格已经被选中,那么我只想选择那些未选中的单元格。
这是我到目前为止的代码:
- (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];
}
}
}
有人对如何做到这一点有任何建议吗?
提前感谢所有回复的人。