我创建了一个带UIButton
的自定义单元格作为复选框。按下时,我将按钮图像更改为选中的复选框。如果我在滚动时检查任何复选框,则会检查未检查的其他单元格。我猜我正在使用标记的复选框对单元格进行出列并重新使用它。我无法弄清楚如何正确设置图像。我创建了一个图像数组来保存每个按钮的图像状态,但这不起作用。这是我的代码:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Celula de Bebidas";
MeuChurrasTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
// Configure the cell...
cell.selectionStyle = UITableViewCellSelectionStyleNone;
cell.precoTextField.adjustsFontSizeToFitWidth = NO;
if (indexPath.section == 0) {
cell.nomeLabel.text = [nomeBebidasAlcoolicas objectAtIndex:indexPath.row]; //nome da bebida
cell.precoTextField.text = [precoBebidasAlcoolicas objectAtIndex:indexPath.row];
[cell.checkboxButton setImage:[imagemBebidasAlcoolicasCheckbox objectAtIndex:indexPath.row] forState:UIControlStateNormal];
} else {
cell.nomeLabel.text = [nomeBebidasNaoAlcoolicas objectAtIndex:indexPath.row];
cell.precoTextField.text = [precoBebidasNaoAlcoolicas objectAtIndex:indexPath.row];
[cell.checkboxButton setImage:[imagemBebidasNaoAlcoolicasCheckbox objectAtIndex:indexPath.row] forState:UIControlStateNormal];
}
// identifica cada botao para depois saber qual foi presssionado.
[cell.checkboxButton setTitle:cell.nomeLabel.text forState:UIControlStateNormal];
return cell;
}
顺便说一下,如果我试试
if (cell == nil)
由于某些原因它永远不会进入if内部,即使第一次调用该表也是如此。
以下是用于设置UIButton图像的代码:
- (void)checkboxPressed:(UIButton *)sender onCell:(MeuChurrasTableViewCell *)cell
{
NSIndexPath *cellPath = [self.tableView indexPathForCell:cell];
// NSLog(@"%@ clicked", [nomeBebidasAlcoolicas objectAtIndex:cellPath.row]);
if ([sender isSelected]) { //Botao nao selecionado
[sender setImage:unselectedImage forState:UIControlStateNormal];
[sender setSelected:NO];
[self.brain.bebidasSelecionadas removeObject:sender.titleLabel.text];
if (cellPath.section == 0)
[imagemBebidasAlcoolicasCheckbox insertObject:unselectedImage atIndex:cellPath.row];
else
[imagemBebidasNaoAlcoolicasCheckbox insertObject:unselectedImage atIndex:cellPath.row];
} else { //Botao selecionado
[sender setImage:selectedImage forState:UIControlStateSelected];
[sender setSelected:YES];
[self.brain.bebidasSelecionadas addObject:sender.titleLabel.text];
if (cellPath.section == 0)
[imagemBebidasAlcoolicasCheckbox insertObject:selectedImage atIndex:cellPath.row];
else
[imagemBebidasNaoAlcoolicasCheckbox insertObject:selectedImage atIndex:cellPath.row];
}
}
任何帮助?