繁体   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