views:

1004

answers:

4

Hi,

I've tried numerous ways of setting the background image of an unselected table cell, but without success:

1- In IB setting the image field
2- cell.contentView.backgroundColor = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:@"list.png"]];
3- cell.imageView.image = [UIImage imageNamed:@"list_selected.png"];

All seem to fail. The image setting for selected cell works, but not for an unselected cell. Anyone having any idea what might be wrong here?

Thanks

+1  A: 

Try setting the backgroundView to an imageView of the image.

gerry3
gerry can you please give some example code. Thanks a lot.
msk
cell.backgroundImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"foo.png"]];
Jason Moore
A: 

try doing this :

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:DateCellIdentifier];
        if (cell == nil) {
            cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:DateCellIdentifier] autorelease]
            UIImageView* img = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"gradient.png"]];
            [cell setBackgroundView:img];
            [img release];
        } 
        cell.textLabel.text = @"Text";
}
Gaurav Verma
Thanks for the reply, Gaurav! I am using a custom built cell for the table view. I tried your above code as is, and putting the background image setting code in the constructor of the custom cell controller class, but still in vain.
msk
post your code here, so that i can look into it.
Gaurav Verma
A: 

I've been doing this using the following UITableViewDelegate method, and setting the cell.backgroundColor property. It gets called last, right before the cell is actually drawn on the screen:

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
if (indexPath.row%2)
    cell.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"TableCell-BG-Dark.png"]];
else 
    cell.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"TableCell-BG-Light.png"]];

}

And yes, I'm using a custom subclass of UITableViewCell.

Shawn Craver
A: 

I've also had problems with trying to change the background colour of cells, i ended up subclassing the cell for different reasons, this is my cell background alternation code:

if (indexPath.row % 2 == 0) {
    cell.contentView.backgroundColor = [UIColor colorWithWhite:230.0/255 alpha:1];
} else {
    cell.contentView.backgroundColor = [UIColor colorWithWhite:242.0/255 alpha:1];
}
Yarek T
note that this seems to work reliably only with a custom cell, not the stock one. In the stock cell the background still applies but all the labels have their background set to white :\
Yarek T