我正在创建一个应用程序,其中我使用包含复选框的自定义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"];
}
答案 0 :(得分: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"];
}
修改强> 但是,如果重新加载了tableview,则不会将该单元格视为已选中。为此,在自定义单元格类头文件中创建一个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"];
}
}