我正在尝试设置我的 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/