0

I'm having a heck of a time getting a cell's backgroundView to display.

The code:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    // assume cell is dequeued correctly (i.e. cell != nil)

    UIView *backgroundView = [[UIView alloc] initWithFrame:cell.frame];
    backgroundView.backgroundColor = [UIColor yellowColor];
    cell.backgroundView = backgroundView;
    [cell.backgroundView setNeedsDisplay];

    return cell;
}

I also tried this in - (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath. Still no luck.

I attempted subclassing the UIView object used as the backgroundView and confirmed drawRect is never being called.

David Nix
  • 3,324
  • 3
  • 32
  • 51

2 Answers2

1

You probably shouldn't do this in the UITableViewCell's own drawRect. Instead, create a custom UIView and add it as a subview.

See also this answer

If all that youre doing is trying to set the color of the tableView's cell then simply set the cell's.ContentView to the desired color.

Community
  • 1
  • 1
Pavan
  • 17,840
  • 8
  • 59
  • 100
  • I did not override `UITableViewCell`'s `drawRect` as per my last sentence. I tested with a subclassed `UIView` object to use as the backgroundView. `drawRect` was never called for that custom view. I'm not messing with the cell's internals. The backgroundView is simply not showing up and I don't know why. – David Nix Jan 14 '14 at 14:52
0

Your code is working for me (I get a bunch of yellow cells) but only if I'm returning numberOfRowsInSection: You sure that is working? Otherwise I get the empty white cells since I told the TableView there is nothing to show.

For example

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 10;
}
ansible
  • 3,569
  • 2
  • 18
  • 29