简体   繁体   中英

Setting background image of custom table view cells

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

Try setting the backgroundView to an imageView of the image.

Code example from Jason Moore (with TomH's correction):

cell.backgroundView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"foo.png"]] autorelease];

cell.backgroundImage no longer exists. Instead use:

cell.backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"foo.png"]];

http://developer.apple.com/library/ios/#documentation/uikit/reference/UITableViewCell_Class/Reference/Reference.html

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.

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";
}

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];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM