cocoa-touch - UITableViewCell 上的 textLabel.backgroundColor 不起作用

标签 cocoa-touch uitableview

我正在尝试设置我的 UITableViewCells 的标签背景颜色,但它什么也不做。我想知道是否有另一种方法可以做到这一点,所以我在问!

我试过这个:

    cell.textLabel.backgroundColor = [UIColor redColor];
cell.backgroundColor = [UIColor redColor];

它不起作用,还有别的吗?

谢谢!

最佳答案

我假设您正在 cellForRowAtIndexPath 中尝试此操作。

根据UITableViewCell class reference :

Note: If you want to change the background color of a cell (by setting the background color of a cell via the backgroundColor property declared by UIView) you must do it in the tableView:willDisplayCell:forRowAtIndexPath: method of the delegate and not in tableView:cellForRowAtIndexPath: of the data source.



所以这样做:
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    cell.backgroundColor = [UIColor redColor]; //must do here in willDisplayCell
    cell.textLabel.backgroundColor = [UIColor redColor]; //must do here in willDisplayCell
    cell.textLabel.textColor = [UIColor yellowColor]; //can do here OR in cellForRowAtIndexPath
}

如果您需要更好地控制单元格显示,一个简单的方法是在 IB 中设计它并从 cellForRowAtIndexPath 中的 Nib 加载它。请参阅 this page 上的“从 Nib 文件加载自定义表格 View 单元格”部分在表 View 编程指南中。

关于cocoa-touch - UITableViewCell 上的 textLabel.backgroundColor 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2610547/

相关文章:

ios - 弹出 View Controller 时的通知

ios - 无法启用解析本地数据存储

uitableview - 在静态 UITableViewCell 中显示 UIButton 的弹出框

iphone - 有什么方法可以将 UILabels 与不同的字体底部对齐吗?

objective-c - 滚动后单元格变空。 (X代码)

objective-c - maskToBounds :YES affecting scroll performance

objective-c - 如何将 url 中的图像添加到 MKAnnotationView 以进行视网膜显示?

ios - 在自定义 tableview 单元格中本地化按钮和标签 [swift]

iphone - 如何在 NSUserDefaults 中设置 NSArray?

ios - Touches 在 TableView 上结束