2009-05-22 118 views

回答

2

更新

顯然,現有的UITableViewCell架構使得它很難改變一個單元格的背景顏色,並將它通過其所有的狀態改變(編輯模式等)很好地工作。

解決方案已發佈在this SO question,它在多個論壇上被評爲「Apple工程師批准的唯一解決方案」。它涉及爲UITableViewCell創建子類併爲子類單元的backgroundView屬性添加自定義視圖。

原帖 - 這個解決方案並不完全工作,但可能仍然是有用的在某些情況下

如果你已經擁有了的UITableViewCell對象,只是改變其contentViewbackgroundColor財產。

如果您需要使用自定義背景顏色創建UITableViewCells,則該過程稍長一點。首先,你需要爲你的UITableView創建一個數據源 - 這可以是實現UITableViewDataSource協議的任何對象。

在該對象中,您需要實現tableView:cellForRowAtIndexPath:方法,該方法在爲表格中單元格的位置提供NSIndexPath時返回UITableViewCell。當您創建該單元格時,您需要更改contentViewbackgroundColor屬性。

不要忘記將UITableView的dataSource屬性設置爲您的數據源對象。

欲瞭解更多信息,可以閱讀這些API文檔:

注意,註冊成爲蘋果開發者需要所有這三個鏈接。

+0

我已經加入此行中的cellForRowAtIndexPath:方法cell.backgroundView.backgroundColor = [的UIColor orangeColor] ;。它仍然顯示在白色背景上的黑色文字 – ebaccount 2009-05-22 18:34:50

+0

我試過cell.backgroundColor = [UIColor orangeColor];這也不起作用 – ebaccount 2009-05-22 18:37:57

0

backgroundView一直在底部。它是顯示圓角和邊緣的那個。你想要的是在backgroundView之上的contentView。它涵蓋了細胞的通常白色區域。

0

這完美的作品對我來說:

NSEnumerator *enumerator = [cell.subviews objectEnumerator]; 
id anObject; 
while (anObject = [enumerator nextObject]) { 
    if([anObject isKindOfClass: [ UIView class] ]) 
     ((UIView*)anObject).backgroundColor = [UIColor lightGrayColor]; 
} 
0

我寫將在iPhone 3.0或更高的工作,但是使用白色背景,否則版本。

在你的UITableViewControllerviewDidLoad方法中,我們添加以下內容:

self.view.backgroundColor=[UIColor clearColor]; 
// Also consider adding this line below: 
//self.tableView.separatorColor=[UIColor clearColor]; 

當你創建你的細胞(在我的代碼,這是我的tableView:cellForRowAtIndexPath:)添加以下代碼:

cell.backgroundColor=[UIColor colorWithPatternImage:[UIImage imageNamed:@"code_bg.png"]]; 
float version = [[[UIDevice currentDevice] systemVersion] floatValue]; 
if (version >= 3.0) 
{ 
    [[cell textLabel] setBackgroundColor:[UIColor clearColor]]; 
} 
11

我知道這是一箇舊帖子,但我相信有些人仍在尋求幫助。您可以使用此設置一個individiual單元格的背景顏色,起初的工作原理:

-(UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath { 
    [cell setBackgroundColor:[UIColor lightGrayColor]]; 

然而,一旦你開始滾動,iPhone將重用的小區,這攪亂不同的背景顏色(如果你想交替他們)。你需要調用tableView:willDisplayCell:forRowAtIndexPath。這樣,在重新加載標識符之前設置背景色。你可以這樣做:

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath { 
    cell.backgroundColor = ([indexPath row]%2)?[UIColor lightGrayColor]:[UIColor whiteColor]; 
} 

最後一行只是一個濃縮的if/else語句。祝你好運!

0

您可以設置backgroundViewbackgroundColor。如果backgroundView不存在,您可以爲其創建一個。

if (!tableView.backgroundView) { 
    tableView.backgroundView = [[UIView alloc] initWithFrame:tableView.bounds]; 
} 
tableView.backgroundView.backgroundColor = [UIColor theMostFancyColorInTheUniverse]; 
0

如果要設置到圖像的單元格的背景,然後使用此代碼:

// Assign our own background image for the cell 
UIImage *background = [UIImage imageNamed:@"image.png"]; 
UIImageView *cellBackgroundView = [[UIImageView alloc] initWithImage:background]; 
cellBackgroundView.image = background; 
cell.backgroundView = cellBackgroundView; 
相關問題