3
votes

I have cell that contain single image view. How it has costraints like that : left(12)top(12)right(12)bot(12).

Its ok, but what i want is, to save that offsets (maybe get rid of bottom offset), but add constraints like height = width, so image will be always square, but, will always have left-top-right offsets equal to 12.

After i add height = width constraint image have not show. Image is downloaded from web, so it isn't available instantly. How to fix it?

3
If you want a square view using IB, here's an answer I gave last March (so it's Swift 3) along with an associated Git repo. stackoverflow.com/questions/42860324/… The trick it to (a) set an aspect of 1:1, along with (2) setting two constraints for margin height/width offsets with different priorities.dfd
Separate comment: if your issue is how to make a square view in code, I can give you a separate Swift 4 answer using layout anchors. It's basically the same type of strategy.dfd

3 Answers

9
votes

Step 1 : Select the View and Add 4 constraints : Top , Left , Right and Aspect Ratio

enter image description here

Step 2 : Select the aspect constraint of the view ( Ex :- X : Y )

enter image description here

Step 3 : Set the Multiplier to 1:1 and you're all set !!!

enter image description here

1
votes

Your constraints seems fine. Roy's answer is also correct (Although it won't work well in a landscape mode as image view will draw outside of the screen since it's trying to match width with height while maintaining top,left and right margins). But still you'll end up with unexpected results because you have set constraints of an ImageView that gets it's image by downloading. So your image view's intrinsic content size is defined by the size of the image at runtime.

What you can do here is to force your imageview not to grow larger than it's bounds. You can simply do this by ticking the "Clip To Bounds" option from Interface Builder.

0
votes

In my case i began playing with views priority and constant and fixed my problem . The default value of constraints priority are 1000 and you can set some of constraint value lower to get your desire views design .

and you can change the value of constants sign ( == , <= , >= ) to get your desire design too

enter image description here