使用 AutoLayout 缩放 UIImageView 以适应宽度

Scaling UIImageView to fit width with AutoLayout

我在 UIScrollView 之上有一个 UIImageView,我希望它适合设备宽度,然后自动设置它的高度以便保留图像比例。

我正在使用自动布局,所以我使用约束将 UIImageView 绑定到屏幕的顶部、左侧和右侧边缘。 我的问题是,UIImageView 会自动调整其框架的大小以适应 UIImage 的高度。之后我无法真正更改此框架,因为它在 UIImageView 和其他 UI 元素之间留有间隙,这些元素应该就在它下面。

我找到了一个变通方法,即在将图像放入 UIImageView 之前手动将其调整为合适的大小,但效率不高,并且在调整视图大小时会产生问题,例如当设备旋转时。

有没有人找到一种方法来强制 UIImageView 更改其框架并保留它而不是使用图像的大小?

皮埃尔

编辑:我添加了屏幕截图以便您可以看到问题。

这是预期的结果:

使用下面的代码

imageView.contentMode = UIViewContentModeScaleAspectFill;
imageView.autoresizingMask =   
    ( UIViewAutoresizingFlexibleBottomMargin
    | UIViewAutoresizingFlexibleHeight
    | UIViewAutoresizingFlexibleLeftMargin
    | UIViewAutoresizingFlexibleRightMargin
    | UIViewAutoresizingFlexibleTopMargin
    | UIViewAutoresizingFlexibleWidth );

能否提供代码?

好的,我找到了适合我的问题的解决方案。

我这样计算我想要的照片的正确高度:

correctedHeight = screenWidth / width * height

之后,我在 updateViewConstraints 方法中以编程方式添加高度约束。

我使用这个代码:

[imageView addConstraint:[NSLayoutConstraint constraintWithItem:imageView attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant: correctImageViewHeight]];

之后要考虑两件事:

  • 每次调用此方法时删除约束(否则最终会出现约束冲突)。为此,我使用 [imageView removeConstraint: imageView.constraints.lastObject] ;
  • [super updateViewConstraints] ; 放入方法中。如果你忘记了,它就会崩溃。

我还没有完成,但我可以很容易地看到如何在设备旋转时更新我的​​ correctHeight 变量。