为什么在iOS 6中分配新图像时会调整UIImageView的大小?

应用程序包含一个包含自定义UITableViewCell的UITableView。 该单元格又​​包含一个UIImageView。

问题是在cellForRowAtIndexPath中设置图像会使图像占用整个UITableViewCell区域:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { CustomCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"CustomCell"]; NSString *path = [[NSBundle mainBundle] pathForResource:@"bigrect" ofType:@"png"]; UIImage *image = [[UIImage alloc] initWithContentsOfFile:path]; cell.imageView.image = image; return cell; } 

在此处输入图像描述

在IB中,已选择“Aspect Fit”作为模式,但更改此字段对结果没有明显影响。

但是,当从IB设置图像时,在我的代码中没有调用cell.imageView.image = image,结果正是我想要看到的。 图像保持在我为IB中的UIImageView定义的边界内,并且不会尝试缩放以适应UITableViewCell的整个垂直高度:

在此处输入图像描述

我正在使用的图像是1307×309像素,如果这很重要的话。 测试在iOS 6.1模拟器上运行。

我从UIIMageView文档中注意到了这一点:

在iOS 6及更高版本中,如果为此视图的restorationIdentifier属性指定值,则会尝试保留显示图像的帧。 具体来说,该类保留视图的bounds,center和transform属性的值以及底层的anchorPoint属性。 在恢复期间,图像视图会恢复这些值,以使图像与之前完全一致。 有关状态保存和还原的工作原理的详细信息,请参阅iOS应用程序编程指南。

但是,我可以找到的文档中没有任何内容可以解决问题。 在“身份”下向IB中的UIImageView添加“Foo”的“恢复ID”并未改变行为。 取消选中“使用Autolayout”也不会改变行为。

在设置图像时,如何防止iOS在UITableViewCell中调整UIImageView的大小?

事实certificate,UITableViewCell显然已经有一个名为“imageView”的属性,它覆盖了整个单元格的背景。 设置此imageView对象的image属性可设置背景图像,而不是我感兴趣的图像。

将我的方法更改为以下内容,同时确保CustomCell具有“myImageView”属性修复了问题:

 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { CustomCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"CustomCell"]; NSString *path = [[NSBundle mainBundle] pathForResource:@"bigrect" ofType:@"png"]; UIImage *image = [[UIImage alloc] initWithContentsOfFile:path]; cell.myImageView.image = image; return cell; } 

这个问题回答了一个稍微不同的问题,这使我指出了正确的方向。