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

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

问题是在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 Documentation注意到了这一点:

In iOS 6 and later,if you assign a value to this view’s restorationIdentifier property,it attempts to preserve the frame of the displayed image. Specifically,the class preserves the values of the bounds,center,and transform properties of the view and the anchorPoint property of the underlying layer. During restoration,the image view restores these values so that the image appears exactly as before. For more information about how state preservation and restoration works,see iOS App Programming Guide.

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

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

解决方法

事实证明,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;
}

This SO answer到一个稍微不同的问题指出了我正确的方向.

相关文章

UITabBarController 是 iOS 中用于管理和显示选项卡界面的一...
UITableView的重用机制避免了频繁创建和销毁单元格的开销,使...
Objective-C中,类的实例变量(instance variables)和属性(...
从内存管理的角度来看,block可以作为方法的传入参数是因为b...
WKWebView 是 iOS 开发中用于显示网页内容的组件,它是在 iO...
OC中常用的多线程编程技术: 1. NSThread NSThread是Objecti...