UITableViewCell背景视图/图像

zhu*_*ber 2 iphone image objective-c uitableview

我在哪里设置cellForRowAt中tableview单元格的backgroundImage ..我该怎么做?这就是我做的方式,它有点工作,但我想知道的是设置backgroundimage(cell.backgroundView)的正确方法,它if(cell==nil)是"if" 内部或外部的正确位置.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {    
    static NSString *cellIdentifier = @"RootViewCellIdentifier";

    UITableViewCell *cell = [_tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier];

        cell.backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"image1.png"]];
    }

    return cell;
}
Run Code Online (Sandbox Code Playgroud)

JOM*_*JOM 6

用来做那个,但现在我更喜欢willDisplayCell:

- (void)tableView:(UITableView *)tableView
  willDisplayCell:(UITableViewCell *)cell
  forRowAtIndexPath:(NSIndexPath *)indexPath
{
    cell.backgroundColor = [UIColor redColor];
}
Run Code Online (Sandbox Code Playgroud)

文档说

表视图在使用单元格绘制行之前将此消息发送到其委托,从而允许委托在显示单元格对象之前对其进行自定义.此方法为委托提供了覆盖表视图前面设置的基于状态的属性的机会,例如选择和背景颜色.委托返回后,表视图仅设置alpha和frame属性,然后仅在向行或向外滑动时为行设置动画.

当使用cellForRowAtIndexPath时,有一些奇怪的特殊情况,其中单元格定制根本无法完全按照我的需要工作.willDisplayCell没有这样的问题.