0

我正在创建一个应用程序,其中我使用TableviewCell包含复选框的自定义,所以imageview如果用户选择一行,我会在其上放置一个未选中的图像,然后我想将图像更改为已选中,那么如何在DidSelectRowAtIndexPath方法上更改此图像?

我试过这个,但它不会工作

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *checkBoxIdentifier = @"checkBox";
    UITableViewCell *cell ;
    NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"CheckBox" owner:self options:nil];
    cell = [nib objectAtIndex:0];
    cell =  [tableView cellForRowAtIndexPath:indexPath];    
    cell.checkBoxImageView.image = [UIImage imageNamed:@"uncheckedimage"];
}
4

1 回答 1

4

只需执行此操作,无需其他任何操作:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //replace 'CustomCell' with your custom cell class name
    CustomCell *cell =  [tableView cellForRowAtIndexPath:indexPath];
    cell.checkBoxImageView.image = [UIImage imageNamed:@"uncheckedimage"];
}

编辑: 但是,如果您的表格视图被重新加载,您将找不到选中的单元格。为此,在您的自定义单元格类头文件中创建一个 BOOL 属性:

@property (retain) BOOL isSelected;

像这样更改您的 didSelectRowAtIndexPath :

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //replace 'CustomCell' with your custom cell class name
    CustomCell *cell =  [tableView cellForRowAtIndexPath:indexPath];
    cell.checkBoxImageView.isSelected = YES;
    [tableView reloadData];
}

取消选择已选中的行:

- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath {
    //replace 'CustomCell' with your custom cell class name
    CustomCell *cell =  [tableView cellForRowAtIndexPath:indexPath];
    cell.checkBoxImageView.isSelected = NO;
    [tableView reloadData];
}

并在您的 cellForRowAtIndexPath 方法中:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
     /*
      initialize and set cell properties like you are already doing
     */
     if(cell.isSelected) {
          cell.checkBoxImageView.image = [UIImage imageNamed:@"uncheckedimage"];
     }
     else {
          cell.checkBoxImageView.image = [UIImage imageNamed:@"checkedimage"];
     }
}
于 2013-10-23T05:35:27.320 回答