2

我在哪里设置 cellForRowAt 中 tableview 单元格的 backgroundImage .. 我该怎么做?我就是这样做的,它有点工作,但我想知道设置背景图像()的正确方法是正确的,它是在“如果”的cell.backgroundView内部还是外部。?if(cell==nil)

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

4 回答 4

6

曾经这样做,但现在我更喜欢willDisplayCell

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

文档说

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

使用 cellForRowAtIndexPath 时,有一些奇怪的特殊情况,其中单元格自定义无法完全按照我的意愿工作。willDisplayCell 没有这样的问题。

于 2012-12-11T21:59:26.753 回答
0
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath  *)indexPath {  
[cell.imageview setImage:[UIImage imageNamed:@"image1.png"]];
   }
return cell;

}

于 2012-12-12T04:32:22.083 回答
0

试试这个可能会有所帮助......

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

         UIImageView *backimg = [[UIImageView alloc] init];
        backimg.frame = CGRectMake(0, 0, 320, 44);
        backimg.tag = 20;
        [cell.contentView addSubview:backimg];
    }
    UIImageView *imag = (UIImageView *)[cell.contentView viewWithTag:20];
    [imag setImage:[UIImage imageNamed:@"sky.png"]];
    return cell;
}
于 2012-12-12T05:38:50.330 回答
-1

为单元格设置背景视图的最佳位置是 tableView:willDisplayCell:forRowAtIndexPath: 方法。

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    cell.backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"image1.png"]];
}
于 2012-12-12T00:08:01.727 回答