DJR
DJR

Reputation: 1

Trouble with Swift, Auto Layout, and stack views

I’ve been working on an app with a grid of buttons. The grid consists of 4 buttons per row, and (currently) 6 rows. In the storyboard, each row of buttons is in a horizontal stack view, and all 6 stack views are in a vertical stack view.

I don’t want all of the buttons to be visible all the time, so I’m turning them on and off with .isHidden. This is causing some problems when I run the app in the simulator:

  1. I want all of the buttons to stay the same size, but if one or more buttons in a given row / stack view are hidden, the remaining buttons in that row adjust their sizes to fill the row. I’m guessing that a combination of constraints on the buttons and settings on the stack view will solve this, but I haven’t come up with the right combination yet.

  2. If I start with, say, the first 3 rows of buttons all unhidden, then try to unhide a button in one of the other rows, all of the buttons disappear. However, if I ‘print’ the .isHidden state of each button, the ones that should be visible have .isHidden = false.

Any ideas for solving either of these problems?

Upvotes: 0

Views: 110

Answers (1)

DonMag
DonMag

Reputation: 77423

To answer your first question...

When you hide a view in a UIStackView, auto-layout treats it as if it is "gone" --- the stack view will re-layout its arrangedSubviews as if that view was never there to begin with.

If you want this result:

enter image description here

Your best bet is probably to set the .alpha property of that view / button to 0. It will be completely invisible (so, in effect, "hidden") and the stack view will retain its current layout. And, controls with .alpha = 0 do not respond to touches (so you can't tap the invisible button).

Upvotes: 0

Related Questions