簡體   English   中英

如何在iphone上的UITableView中設置單元格的背景顏色?

[英]How can I set the background color of a cell in UITableView on iphone?

如何在UITableView中設置單元格的背景顏色?

謝謝。

我知道這是一個老帖子,但我相信有些人仍在尋求幫助。 您可以使用它來設置單個單元格的背景顏色,這首先起作用:

-(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語句。 祝好運!

更新

顯然,現有的UITableViewCell框架使得更改單元格的背景顏色非常困難,並且通過其所有狀態更改(編輯模式等)使其工作良好。

這個SO問題上已經發布了一個解決方案,它在幾個論壇上被稱為“Apple工程師批准的唯一解決方案”。 它涉及子類化UITableViewCell並為子類單元的backgroundView屬性添加自定義視圖。

原始帖子 - 此解決方案無法完全運行,但在某些情況下可能仍然有用

如果您已經擁有UITableViewCell對象,只需更改其contentViewbackgroundColor屬性即可。

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

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

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

有關詳細信息,您可以閱讀以下API文檔:

請注意,所有這三個鏈接都需要注冊為Apple開發人員。

這對我很有用:

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

您可以設置backgroundColorbackgroundView 如果backgroundView不存在,您可以為它創建一個。

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

我寫的版本將在iPhone 3.0或更高版本中運行,否則將回退到白色背景。

UITableViewController viewDidLoad方法中,我們添加以下內容:

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

如果要將單元格的背景設置為圖像,請使用以下代碼:

    // 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;

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM