1

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?

mav
  • 85
  • 11

1 Answers1

2

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
Malik
  • 3,763
  • 1
  • 22
  • 35
  • Thank you for your suggestion - I'll try. – mav May 17 '18 at 09:37
  • Oh boy - that was it - thanks a lot once again! Still, auto layout is such a PITA for me right now because I cannot find a way to efficiently trace and debug all the constraints. Xcode is so clumsy :( – mav May 17 '18 at 09:47
  • @mav Glad to be of help. Constraints might seem a bit overwhelming but once you get used to the idea, they are quite powerful and you can do a lot more with a lot less. If your problem has been resolved. please mark the answer as accepted – Malik May 18 '18 at 00:33