iphone - 如何更改所有 UITableViewCells 的背景颜色

标签 iphone objective-c ios ipad uitableview

我有一个非常简单的 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/

相关文章:

iphone - UITableViewCell textLabel 宽度不变

iphone - iOS 7 蓝牙 - 即使手机重启后也能在后台处理事件的应用程序

objective-c - 将 sqlite3 添加到框架中?

IOS Xamarin - 实时绘图画线

由 iBeacon 触发的 iOS 8 后台位置更新

iphone - UIViewController shouldAutorotateToInterfaceOrientation 不能正常工作

iOS 8 建议的应用程序图标锁屏

ios - 我的应用程序从昨天开始仍在处理,我今天更改了构建版本并再次上传。iTunes Connect 上缺少今天的构建版本?

ios - [object] 没有可见的@interface 声明选择器 [method]

ios - xcodebuild - 设置构建目录不会生成 dSYM