简体   繁体   中英

Set UIImage's height equal to its width

My question is exactly what the title says. I am setting the width of the imageview equal to the width of the screen (through the storyboard, I set the left and right constraints to 0) I tried:

imageView.frame = CGRect(x: 0, y: 0, width: imageView.frame.width, height: imageView.frame.width)

but it's not working. Not sure if it's an issue with the rest of my layout (the image is in a stackview), or my code.

Here is my entire layout: 在此处输入图片说明 Thanks for any help.

该代码不起作用,因为imageView.frame.width为0。您可以在情节提要中将堆栈视图约束的宽高比设置为1:1,并将图像视图的左右约束设置为堆栈视图的0。

in my experience, autolayout does not mix with setting a frame; it could be argued the whole point is that frame is set based on the autolayout constraints.

More to the point, I think I get a vague idea of what you wanted to do:

  1. You want to have an image that would be the whole width of the screen (or some proportion of it);
  2. You want it to be square (or some other ratio);
  3. You want it be in a vertical UIStackView so that you can automatically align captions and so on.

For a bit of a background, UIImageView elements have "intrinsic" sizes, set to the size of the image that is shown in them and will assume those sizes if not otherwise constrained. If you don't specify a size for an UIStackView, it will be sized based on intrinsic sizes of elements in it; if you specify the size for it, it will try to resize elements in it to fit.

To achieve the scenario outlined above, you want to set width to UIStackView (by, say, constraining it to be the same width as the container view) – this will force the same width to be applied to the UIImageView.

The height of the UIImageView will still be based on the height of the image it displays. To make the UIImageView square, you can set aspect ratio constraint on it to 1:1.

Good luck and please let me know if I misunderstood what you wanted to achieve or if you need further clarification.

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