我有一个非常简单的 View Controller ,它只有一个 UITableView
和一个 UIButton
,当点击按钮时,我想更改所有 的背景颜色code>UITableViewCells
变为绿色,因为有些单元格不可见,我使用这个循环来完成我需要的:
- (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
的默认行为上,它实际上不会创建不可见的单元格,直到它们可见为止!所以不幸的是,上面的代码仅适用于可见单元格。问题是,如何在点击按钮时更改所有单元格的颜色?
附注这个非常简单的项目示例 can be downloaded here .
提前致谢。
最佳答案
你不必这样做
只用一个变量来保存单元格的背景颜色
UIColor cellColor;
然后当你改变颜色调用
[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 ;
}
关于iphone - 如何更改所有 UITableViewCells 的背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10213364/