2010-02-16 265 views
2

我試過設置未選定表格單元格的背景圖像的多種方式,但沒有成功:設置背景圖片

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

似乎都失敗。所選單元的圖像設置適用,但不適用於未選定單元。任何人有任何想法在這裏可能是錯誤的?

感謝

回答

19

嘗試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

1

嘗試這樣做:

- (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

2

我一直在做這個使用下面的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

0

我也有問題,試圖改變細胞的背景顏色,我結束了繼承的原因不同的單元格,這是我的手機背景交替代碼:

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