简体   繁体   中英

Resizing subview containing image in UIStackView

A while ago I thought it might be a good idea to replace my own layout for a number of views inside a scrollview with a UIStackView. But after more than a week of frustration I'm asking for help: I'd like to place subviews like these:

inside a vertical UIStackView (alignment fill, distribution fill). The UIImageView's content mode is aspect fill, the image is set at runtime and can change at runtime (especially its aspect). I'd like the subviews to horizontally fill the stack view and to resize vertically in order to keep the image's aspect ratio intact.

When I don't add any special constraints, I don't get layout warnings, but the subview inside my stack view doesn't resize when I change the image. If I add an aspect constraint to the UIImageView every time the image is being set, I get a layout warning the first time I change the image and afterwards it doesn't resize the subview.

Can someone of you auto layout wizards please help me out?

You cannot set a constraint on an ImageView based on an image that will be loaded later. What you should do instead is

  • Set a height constraint on your ImageView
  • Connect an IBOutlet to this constraint
  • When the image is loaded, find out it's aspect ratio
  • Calculate the desired height since you already know the width (stackView's width)
  • Set this height to your ImageView 's height constraint

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM