UITableViewCell backgroundView绘制rect未被调用

时间:2014-01-14 07:01:23

标签: ios cocoa-touch uitableview

我正好想要显示一个单元格backgroundView

代码:

- (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;
}

我也在- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath尝试了这个。仍然没有运气。

我尝试将用作backgroundView的UIView对象子类化,并确认永远不会调用drawRect

2 个答案:

答案 0 :(得分:1)

你可能不应该在UITableViewCell自己的drawRect中这样做。而是创建一个自定义UIView并将其添加为子视图。

另见answer

如果您正在尝试设置tableView单元格的颜色,则只需将单元格的.ContentView设置为所需的颜色。

答案 1 :(得分:0)

你的代码正在为我工​​作(我得到了一堆黄色单元格)但是只有当我返回numberOfRowsInSection:你确定它有效吗?否则我得到空的白色单元格,因为我告诉TableView没有什么可以显示。

例如

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 10;
}