0

我有一个表格视图,它由包含图像视图的自定义表格视图单元格组成。在cellForRowAtIndexPath我设置每个单元格的图像。我希望在选择单元格时更改图像,所以在didSelectRowAtIndexPath我获取单元格并更改图像时,没有问题。但是,当我滚动表格(阅读:表格重新加载单元格)时,新图像不再存在。此外,当不再选择单元格时,我希望图像切换回原始图像。

我尝试过以下操作cellForRowAtIndexPath

if(cell.isSelected){
cell.imageview.image = [UIImage ImageNamed: @"selected.png"];
}
else
cell.imageview.image = [UIImage ImageNamed: @"not selected.png"];

我也尝试过使用 BOOL 值cell.highlightedcell.selected无济于事。

任何想法表示赞赏。

4

2 回答 2

2

尝试使用类型的类selectedCellIndexPath变量NSIndexPath。在didSelectRow...你设置它的价值,并在cellForRow...你写:

if([selectedCellIndexPath isEqual:indexPath]){
    cell.imageview.image = [UIImage ImageNamed: @"selected.png"];
} else {
    cell.imageview.image = [UIImage ImageNamed: @"not selected.png"];
}

编辑:

或者你可以简单地写:

if([indexPath isEqual:[tableView indexPathForSelectedCell]]){
    cell.imageview.image = [UIImage ImageNamed: @"selected.png"];
} else {
    cell.imageview.image = [UIImage ImageNamed: @"not selected.png"];
}

但第一个解决方案效率更高一些。

于 2013-01-22T18:49:17.807 回答
0

如果您有一个带有图像名称的数组,那么最简单的方法是更改​​数组中选定索引处的名称并重新加载表......像这样:

myImageArray = [[NSMutableArray alloc] init];
[myImageArray addObject:@"name1.jpg"];
[myImageArray addObject:@"name2.jpg"];
// etc..

而在 cellForRowAtIndexPath 方法中:

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
}

[cell.imageView setImage:[UIImage imageNamed:[myImageArray objecAtIndex:indexPath.row]]];

}

在 didSelectRowAtIndexPath 中:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

[myImageArray setObject:@"newName.jpg" atIndexedSubscript:indexPath.row];
[tableView reloadData];

}
于 2013-01-22T19:00:53.480 回答