Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Horizontal squares with equal spacing between

Tags:

ios

swift

I'm trying to make a row of 5 equal squares (each 50x50) with spacing 20dp between them. I don't want anything to stretch, but at the same time I want to make it so that if I hide one of the squares, the others move over.

For example:

+-----+    +-----+    +-----+    +-----+    +-----+
| 50  | 20 | 50  | 20 | 50  | 20 | 50  | 20 | 50  |
| x50 |    | x50 |    | x50 |    | x50 |    | x50 |
+-----+    +-----+    +-----+    +-----+    +-----+

Then, if I set the middle square to isHidden = true, I'd want the others to move over:

+-----+    +-----+    +-----+    +-----+
| 50  | 20 | 50  | 20 | 50  | 20 | 50  |
| x50 |    | x50 |    | x50 |    | x50 |
+-----+    +-----+    +-----+    +-----+

Is this possible? My first thought was a stack view, but I don't think that would work since they're meant to adjust spacing.

like image 295
user86516512 Avatar asked Nov 23 '25 11:11

user86516512


2 Answers

Use UIStackView...

  • No Width or Trailing constraint.
  • Distribution: Fill
  • Spacing: 20
  • give each subview Width and Height constraints of Equal to Constant: 50

You end up with:

   1          2          3          4          5
+-----+    +-----+    +-----+    +-----+    +-----+
| 50  | 20 | 50  | 20 | 50  | 20 | 50  | 20 | 50  |
| x50 |    | x50 |    | x50 |    | x50 |    | x50 |
+-----+    +-----+    +-----+    +-----+    +-----+

Remove view #3 with:

let v = stackView.arrangedSubviews[2]
v.removeFromSuperview()

You now have:

   1          2          4          5
+-----+    +-----+    +-----+    +-----+
| 50  | 20 | 50  | 20 | 50  | 20 | 50  |
| x50 |    | x50 |    | x50 |    | x50 |
+-----+    +-----+    +-----+    +-----+

You'll get the same result with:

let v = stackView.arrangedSubviews[2]
v.isHidden = true

The stack view will hide view #3, removing the space it is occupying. If you set .isHidden back to false, the view will re-appear in its original position, shifting views 4 and 5 back to their original spots.

like image 141
DonMag Avatar answered Nov 26 '25 02:11

DonMag


You should use StackView. But to hide some square you need to set its alpha to 0, instead of make it hidden. In this case layout will stay the same - you can hide some squares, and other will stay on their positions. If you need other squares to fill empty space with given spacing between elements - use isHidden property.

  • For example there are 5 circles: 0-0-0-0-0.

  • Lets set 3 circle isHidden: 0-0-0-0.

  • And now set alpha of 3 circle to zero: 0-0- -0-0.

like image 31
Dmytro Yashchenko Avatar answered Nov 26 '25 02:11

Dmytro Yashchenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!