2013-05-17 23 views
1

我有一个表格视图与分组的单元格。我希望这个单元格包含一个图像。这里是我的代码中插入图像,使之适合在细胞:不能适合tableViewCell中的图像

   logoCell = [tableView dequeueReusableCellWithIdentifier:LogoCellIdentifier]; 
      if (logoCell == nil) { 
       logoCell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:LogoCellIdentifier]; 
      } 

      UIImageView *imgView=[[UIImageView alloc] initWithFrame:CGRectMake(0, 0, logoCell.frame.size.width, 80)]; 
      [imgView setImage:image]; 

      [logoCell.contentView addSubview:imgView]; 

但我的形象比单电池的宽度大时的tableView是显示器。我怎样才能使它适合细胞?

回答

2

添加图像作为tableViewCell的背景颜色,你会得到漂亮的圆角。否则,分组的单元格不会掩盖图像。您还需要设置UIImageView的contentMode,以便将所有内容都缩放到单元格中。

UIImageView *imgView=[[UIImageView alloc] initWithFrame:CGRectMake(0, 0, logoCell.frame.size.width, 80)]; 
imgView.contentMode = UIViewContentModeScaleAspectFit; 
cell.backgroundColor = [UIColor colorWithPatternImage:imgView.image]; 
+0

谢谢,这正是我想要的 – louftansa

0

创建UIImageView这样:

UIImageView *imgView = [[UIImageView alloc] initWithImage:image]; 
imgView.frame = CGRectMake(0, 0, logoCell.frame.size.width, 80); 

附注 - 确保您不添加每次新UIImageView到细胞。你只想添加一次。滚动时单元格会被重用。根据您如何实现代码,您可以轻松地将多个图像视图添加到单元格。

+0

感谢您的注意,我会牢记这一点。 – louftansa

1

如何将图像视图添加到UITableViewCell s取决于您想要对图像视图执行的操作。如果您想让图像成为单元格内容的一部分,请在创建单元格时添加它。

logoCell = [tableView dequeueReusableCellWithIdentifier:LogoCellIdentifier]; 
if (logoCell == nil) { 
    logoCell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:LogoCellIdentifier]; 

    // ADD IMAGEVIEW ONLY WHEN CREATING CELL 
    UIImageView *imgView=[[UIImageView alloc] initWithFrame:CGRectMake(0, 0, logoCell.frame.size.width, 80)]; 
    [logoCell.contentView addSubview:imgView]; 

    // DONT ALLOW IMAGE OVERFLOW 
    imgView.clipsToBounds = YES; 
} 

// SET YOUR IMAGE EVERY TIME 
[imgView setImage:image]; 

如果你想将其设置为背景视图,您应该设置单元格的backgroundView财产tableView:willDisplayCell:forRowAtIndexPath。确保图像视图与单元大小相同。

UIImageView *imgView = [[UIImageView alloc] initWithFrame: cell.bounds]; 
imgView.image = image; 
cell.backgroundView = imgView;