我正在基于我在XIB文件中创建的UITableViewCell原型构建一个表。单元格由几个标签和一个图像视图组成,需要拉伸以适应整个设备宽度。一旦拉伸宽度,我也想将高度拉伸到相同的比例,这样我的图像就可以一致地缩放。
我的结果好坏参半。我已经能够使用以下代码适当地调整CELL的大小:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
//pull the image from the array based on the indexPath
NSUInteger row = [indexPath row];
CITImage *image = [report.reportImages objectAtIndex:row];
UIImage *img = [UIImage imageWithData:image.imageData];
//see how we need to scale the image to make it fit within the full width of the screen
float scale = tableView.frame.size.width /img.size.width;
float imgHeight = img.size.height * scale;
//return the necessary cell height
return imgHeight;
}
问题是单元格内的UIImageView没有正确调整大小。我正在使用以下代码在准备好绘制单元格时设置单元格的属性:
-(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
//pull the image from the array based on the indexPath
NSUInteger row = [indexPath row];
CITImage *image = [report.reportImages objectAtIndex:row];
UIImage *img = [UIImage imageWithData:image.imageData];
//attempt to get a reusable cell
CITImageCell *cell;
cell= [tableView dequeueReusableCellWithIdentifier:@"CITImageCellIdentifier"];
if (cell == nil) {
// Load the top-level objects from the custom cell XIB.
NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"CITImageCell" owner:self options:nil];
cell = [topLevelObjects objectAtIndex:0];
}
//see how we need to scale the image to make it fit within the full width of the screen
float scale = tableView.frame.size.width /img.size.width;
float imgHeight = img.size.height * scale;
NSLog (@"Height %f",cell.imageView.frame.size.height);
//size the image view
cell.imageView.frame = CGRectMake(0,34, tableView.frame.size.width, imgHeight+34 );
NSLog (@"Height %f",cell.imageView.frame.size.height);
//assign the image
cell.imageView.image = img;
//return the cell ready to go
return cell;
}
两个NSLog语句验证高度值是否正确计算,但是当图像显示在屏幕上时,它的大小正确。大多数时候它的大小与XIB文件中定义的大小相同,但有时它需要正确的高度。我还没有找到一个很好的模式。它永远不是表中的第一项,总是第二项,有时是第四项和第五项。
还在挖掘文档和其他人的故事,最让我感到高兴的是,我可以正确地调整单元格大小,并且图像高度计算正确,但它只在某些时候显示。
有任何帮助吗?显示我正在经历的屏幕截图的链接如下(是的,我昨晚正在观看辩论)
谢谢!
答案 0 :(得分:27)
我遇到了同样的问题。经过一个小时的工作,我意识到发生了什么!
问题是UITableViewCell已经有imageView
!!
如果您对imageView
使用 SAME 属性名UIImageView
,系统会以某种方式修改您定义的imageView
。
所以解决方案 DONT 使用名称imageView
,尝试使用其他名称。
例如:
@property (nonatomic, weak) UIImageView *myImageView;
至少为我工作。 :)
答案 1 :(得分:2)
搞定了!我不知道这是否是唯一的方法,但我必须在运行时创建UIImageView并手动将其添加到单元格而不是尝试调整XIB文件中的一个。任何人都可以解释为什么会这样吗?
这是我结束的代码:
CGRect imageFrame = CGRectMake(0,34, tableView.frame.size.width, imgHeight);
UIImageView *imgView = [[UIImageView alloc] initWithFrame:imageFrame];
[imgView setImage:img];
[cell addSubview:imgView];
答案 2 :(得分:0)
我认为我错过的另一个答案是使用IB将UIImageView的边界绑定到容器单元格的底部。我当时不知道我能做到这一点,但有朋友告诉我怎么做,我想我会在这里提到它。