如何在iphone上的UITableView中设置单元格的背景颜色? [英] How can I set the background color of a cell in UITableView on iphone?

查看:107
本文介绍了如何在iphone上的UITableView中设置单元格的背景颜色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆