如何更改所有UITableViewCells的backgroundColor [英] How to change the backgroundColor for all UITableViewCells

查看:38
本文介绍了如何更改所有UITableViewCells的backgroundColor的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常简单的视图控制器,它只有一个UITableView和一个UIButton,当点击按钮时,我想将所有UITableViewCells的背景颜色更改为绿色,从而给出一些细胞不可见,我使用此循环来完成所需的操作:

I have a very simple view controller which has only a UITableView and a UIButton, when tapping the button, I want to change the color of the background of all UITableViewCells to green, giving that there are some cells not visible, I use this loop to accomplish what I need:

 - (IBAction)click:(id)sender {

for (int row = 0; row < [self.tableView numberOfRowsInSection:0]; row++)  {

    NSIndexPath* cellPath = [NSIndexPath indexPathForRow:row inSection:0];
    UITableViewCell* cell = [self.tableView cellForRowAtIndexPath:cellPath];

    cell.backgroundColor = [UIColor greenColor];

 }

}

问题出在UITableView的默认行为上,它实际上不会创建不可见的单元格,直到它们可见为止!因此不幸的是,以上代码仅适用于可见单元格.问题是,如何在点击按钮时更改所有单元格的颜色?

the problem is with the default behavior of the UITableView, it does not actually create the invisible cells until they are visible !! so the above code unfortunately works ONLY on visible cells. The question is, how can I change the color of all cells on button tap ?

p.s.此非常简单的项目示例可在此处下载.

p.s. this very simple project sample can be downloaded here.

先谢谢您.

推荐答案

您不必这样做

只需使用变量保存单元格的backgroundColor

just use a variable to save the backgroundColor of cells

UIColor cellColor;

然后当您更改颜色调用时

then when you change the color call

[tableView reloadData];

然后

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
     UITableViewCell *cell = yourcell;

     ...
     ...
     ...

     cell.backgroundColor = cellColor;

     return cell ;
}

完成了!

更新

对不起,试试这个

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
     UITableViewCell *cell = yourcell;

     ...
     ...
     ...
    cell.textLabel.backgroundColor = [UIColor clearColor];
UIView* bgview = [[UIView alloc] initWithFrame:cell.bounds];
bgview.backgroundColor = [UIColor greenColor];
    [cell setBackgroundView:bgview];

     return cell ;
}

这篇关于如何更改所有UITableViewCells的backgroundColor的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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