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

前端之家收集整理的这篇文章主要介绍了为什么在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到一个稍微不同的问题指出了我正确的方向.

原文链接:https://www.f2er.com/iOS/333845.html

猜你在找的iOS相关文章