如何在TableView上设置Cell的颜色?

时间:2013-05-08 11:55:38

标签: iphone ios objective-c tableview cell

我希望整个单元格用蓝色打印,但它只显示一个小带。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *cellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil) {
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier];
}
[cell.contentView setBackgroundColor:[UIColor blueColor]];    
cell.textLabel.text = [NSString stringWithFormat:@"%@", [cat objectAtIndex:indexPath.row]];    
return cell;}

我的屏幕截图是:

enter image description here

4 个答案:

答案 0 :(得分:2)

[cell.contentView setBackgroundColor:[UIColor blueColor]]; line:

之后添加此行
cell.textLabel.backgroundColor = [UIColor clearColor];

答案 1 :(得分:1)

答案: tableView:willDisplayCell:forRowAtIndexPath:

    - (void)tableView:(UITableView *)tableView
  willDisplayCell:(UITableViewCell *)cell
forRowAtIndexPath:(NSIndexPath *)indexPath
    {
        cell.backgroundColor = [UIColor blueColor];
    }

答案 2 :(得分:1)

由于UITableView在选择过程中更改了单元格的背景颜色,因此必须实现tableView:willDisplayCell:forRowAtIndexPath:并在其中设置单元格背景。您应该设置整个单元格的背景而不仅仅是其contentView,否则附件视图将不会突出显示。

- (void)tableView:(UITableView *)tableView
  willDisplayCell:(UITableViewCell *)cell
forRowAtIndexPath:(NSIndexPath *)indexPath
{
    // ...
    cell.backgroundColor = ...;
}

您可能还需要使单元格中的各个子视图具有透明的背景颜色。

cell.titleLabel.backgroundColor = [UIColor clearColor];
cell.titleLabel.opaque = NO;

答案 3 :(得分:1)

使用此

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *cellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil) {
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier];
}
[cell.contentView setBackgroundColor:[UIColor blueColor]];    
cell.textLabel.backgroundColor = [UIColor clearColor];
cell.textLabel.text = [NSString stringWithFormat:@"%@", [cat objectAtIndex:indexPath.row]];    
return cell;}