设置背景图片

问题描述:

我试过设置未选定表格单元格的背景图像的多种方式,但没有成功:设置背景图片

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

似乎都失败。所选单元的图像设置适用,但不适用于未选定单元。任何人有任何想法在这里可能是错误的?

感谢

尝试backgroundView设置为图像的ImageView的。从杰森·穆尔

代码示例(与TomH的校正):

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

格里可以请您给一些示例代码。非常感谢。 – msk 2010-02-16 08:42:05

+2

cell.backgroundImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@“foo.png”]]; – 2010-03-05 16:31:24

+1

我相信上面会泄漏 - 在末尾添加一个autorelease – TomH 2011-05-18 16:12:35

尝试这样做:

- (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"; 
} 
+0

感谢您的回复,Gaurav!我正在为表视图使用定制的单元格。我按照原样尝试了上述代码,并将背景图像设置代码放置在自定义单元控制器类的构造函数中,但仍然徒劳无功。 – msk 2010-02-16 09:06:40

+0

在此处发布您的代码,以便我可以查看它。 – 2010-02-16 13:07:56

我一直在做这个使用下面的UITableViewDelegate方法,并设置电池。 backgroundColor属性。它被调用最后,对之前的细胞实际上是在屏幕上绘制:

- (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"]]; 

}

是的,我使用的UITableViewCell的自定义子类。

+0

你是天才! – Zepplock 2011-08-31 06:03:50

我也有问题,试图改变细胞的背景颜色,我结束了继承的原因不同的单元格,这是我的手机背景交替代码:

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

请注意,这似乎只能使用自定义单元,而不是股票可靠工作。在股票单元格中背景仍然适用,但所有标签都将其背景设置为白色:\ – 2010-02-16 18:04:40

cell.backgroundImage不再存在。而是使用:

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

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