如何在didSelectRowAtIndexPath中更改单元格的背景图像

时间:2014-01-06 11:31:13

标签: ios iphone ipad uitableview uiimageview

我想在选择单元格时更改单元格的背景图像。

我尝试过这种语法:

- (UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath{
 //for adding image
 cell.ImgCateg.image=[UIImage imageNamed:[ImgArr objectAtIndex:indexPath.row]];
     ...
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    CRHomeCategCell *cell = (CRHomeCategCell*)[_tblCateg cellForRowAtIndexPath:indexPath];
    cell.ImgCateg.image = [UIImage imageNamed:@"DefaultBg.png"];
}
  

这会改变前景中的图像而不是后台。

请提前帮助和致谢。

2 个答案:

答案 0 :(得分:2)

您可以在cellForRowAtIndexPath方法中设置UITableviewCell的属性 setSelectedBackgroundView

喜欢,

- (UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath{
{
....
UIImageView *normalCellBG = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, cell.frame.size.width, cell.frame.size.height)];

[normalCellBG setImage:[UIImage imageNamed:@"box_nonselected.png"]];//Set Image for Normal
[normalCellBG setBackgroundColor:[UIColor clearColor]];
[cell setBackgroundView:normalCellBG];


UIImageView *selecetedCellBG = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, cell.frame.size.width, cell.frame.size.height)];
[selecetedCellBG setImage:[UIImage imageNamed:@"box_selected.png"]];//Set Name for selected Cell
[selecetedCellBG setBackgroundColor:[UIColor clearColor]];
[cell setSelectedBackgroundView:selecetedCellBG ];

}

this那么问题。

答案 1 :(得分:1)

您可以通过以下方式执行此操作:

UIImage *cellImage = [UIImage imageNamed:@"myimage.png"];
UIImageView *cellView = [[UIImageView alloc] initWithImage:cellImage];
cellView.contentMode = UIContentViewModeScaleToFill; 
cell.backgroundView = cellView;