UITableViewCell背景视图/图像

时间:2012-12-11 21:16:53

标签: iphone objective-c image uitableview

我在哪里设置cellForRowAt中tableview单元格的backgroundImage ..我该怎么做?这就是我做的方式,它有点工作,但我想知道是用于设置backgroundimage(cell.backgroundView)的正确方法,它是在if(cell==nil)内还是在“if”之外的正确位置。?< / p>

- (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 个答案:

答案 0 :(得分:6)

用于做到这一点,但现在我更喜欢 willDisplayCell

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

文档说

  

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

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

答案 1 :(得分:0)

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath  *)indexPath {  
[cell.imageview setImage:[UIImage imageNamed:@"image1.png"]];
   }
return cell;

}

答案 2 :(得分: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;
}

答案 3 :(得分:-1)

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

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    cell.backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"image1.png"]];
}
相关问题