我正在尝试编写代码来根据它在表格中的位置来修改单元格的背景颜色。虽然以下代码“有效”,但它只会影响传递给它的单元格。空单元格不受影响。
- (void)tableView: (UITableView*)tableView willDisplayCell: (UITableViewCell*)cell forRowAtIndexPath: (NSIndexPath*)indexPath
{
if(!indexPath.row%2)
{
cell.backgroundColor = [UIColor colorWithRed: 0.0 green: 0.0 blue: 1.0 alpha: 1.0] ;
NSLog(@"Blue");
}
else{
cell.backgroundColor = [UIColor whiteColor];
NSLog(@"white");
}
cell.textLabel.backgroundColor = [UIColor clearColor];
cell.detailTextLabel.backgroundColor = [UIColor clearColor];
}
如果列表中的项目很少,我如何影响显示的其余单元格(如果为空)?
“空”单元格是指当数据源没有足够的数据来填充表视图的整个视图时显示的占位符单元格。例如,如果你可以容纳10个单元格,但只有5个数据,那么你只需要处理5个单元格 - 接下来的5个是空的,据我所知,无法访问。
答案 0 :(得分:2)
我想你只想更改“空”单元格的背景......然后你可以在UITableView的InterfaceBuilder中更改backgroundColor。 但它会影响所有空单元格。
您还可以更改分隔符类型。
另外,请看一下:http://www.zenbrains.com/blog/en/2010/06/color-de-fondo-de-celdas-vacias/
编辑:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
// 7 depends on how many cell is shown
return ([source count] <= 7) ? 7 : [source count];
}
答案 1 :(得分:1)
如果设置了单元格contentView的backgroundColor属性,而不是单元格的backgroundColor,它应该有效:
cell.contentView.backgroundColor = [UIColor colorWithRed: 0.0 green: 0.0 blue: 1.0 alpha: 1.0] ;
答案 2 :(得分:0)
你应该实施
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
在您的委托中并根据需要初始化单元格。
答案 3 :(得分:0)
尝试添加以下行
[[cell contentView] setBackgroundColor:[UIColor colorWithRed:0 green:128/255.f blue:0 alpha:1]];
方法中的
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
与您在willDisplayCell方法中使用的逻辑相同
如此处所示:http://www.zenbrains.com/blog/en/2010/06/color-de-fondo-de-celdas-vacias/
*请注意我们更改了[cell contentView]
的背景颜色