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

2024-01-28

应用程序包含一个 UITableView,其中包含一个自定义 UITableViewCell。该单元格又​​包含一个 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 的整个垂直高度:

我使用的图像是 1307x309 像素,以防万一这很重要。测试在 iOS 6.1 模拟器上运行。

我从UIImageView文档 http://developer.apple.com/library/ios/#documentation/uikit/reference/UIImageView_Class/Reference/Reference.html:

在 iOS 6 及更高版本中,如果您为此视图的restoreIdentifier 属性分配一个值,它会尝试保留显示图像的框架。具体来说,该类保留视图的bounds、center和transform属性以及底层的anchorPoint属性的值。在恢复过程中,图像视图会恢复这些值,以便图像看起来与以前完全相同。有关状态保存和恢复如何工作的更多信息,请参阅 iOS 应用程序编程指南。

然而,我在文档中或其他地方找不到任何解决该问题的方法。将“Foo”的“恢复 ID”添加到“Identity”下 IB 中的 UIImageView 中并没有改变行为。取消选中“使用自动布局”也不会改变行为。

如何防止 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;
}

这个答案 https://stackoverflow.com/a/14214337/54426一个稍微不同的问题为我指明了正确的方向。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

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

随机推荐