如何在iphone上的UITableView中设置单元格的背景颜色?

eba*_*unt 4 iphone objective-c

如何在UITableView中设置单元格的背景颜色?

谢谢.

ale*_*ran 11

我知道这是一个老帖子,但我相信有些人仍在寻求帮助.您可以使用它来设置单个单元格的背景颜色,它首先起作用:

-(UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath {
     [cell setBackgroundColor:[UIColor lightGrayColor]];
Run Code Online (Sandbox Code Playgroud)

但是,一旦你开始滚动,iphone将重复使用不同背景颜色的单元格(如果你试图交替它们).您需要调用tableView:willDisplayCell:forRowAtIndexPath.这样,在加载重用标识符之前设置背景颜色.你可以这样做:

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

最后一行只是一个浓缩的if/else语句.祝好运!