如何在iphone上的UITableView中设置单元格的背景颜色? [英] How can I set the background color of a cell in UITableView on iphone?
问题描述
如何在UITableView中设置单元格的背景颜色?
How can I set the background color of a cell in UITableView?
谢谢。
推荐答案
我知道这是一个老帖子,但我相信有些人仍在寻求帮助。您可以使用它来设置单个单元格的背景颜色,它首先起作用:
I know this is an old post, but I am sure some people are still looking for help. You can use this to set the background color of an individiual cell, which works at first:
-(UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath {
[cell setBackgroundColor:[UIColor lightGrayColor]];
然而,一旦你开始滚动,iphone将重复使用不同背景颜色的单元格(如果你试图替代他们)。您需要调用tableView:willDisplayCell:forRowAtIndexPath。这样,在加载重用标识符之前设置背景颜色。你可以这样做:
However, once you start scrolling, the iphone will reuse cells, which jumbles different background colors (if you are trying to alternate them). You need to invoke the tableView:willDisplayCell:forRowAtIndexPath. This way, the background color gets set before the reuse identfier is loaded. You can do it like this:
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
cell.backgroundColor = ([indexPath row]%2)?[UIColor lightGrayColor]:[UIColor whiteColor];
}
最后一行只是一个浓缩的if / else语句。祝你好运!
The last line is just a condensed if/else statement. Good luck!
这篇关于如何在iphone上的UITableView中设置单元格的背景颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!