Search code examples
iosswiftxcodeuiimageviewuistackview

UI in Xcode (Swift): I only want the collapsing functionality of UIStackView, not standardised spacing. Still worth using one?


I have a UITableViewCell, in which I'd like to have two UILabels, a UIImageView, followed by a UIButton beneath (all stacked vertically). Diagrammatically, it would look like this:


UILabel

1 point vertical spacing

UILabel2

6 points vertical spacing

UImageView

4 points vertical spacing

UIButton

Any two of these may not be present (except the two labels), and the rest must resize accordingly, collapsing the empty space. Would a UIStackView be worth using here, keeping in mind that custom spacing would need to be used.

As an example, in a stack view, the UIImageView could be easily collapsed if we did not have an image to show, whereas without one, I can't think of a way of doing it without messing about with height constraints of the UIImageView in code. Perhaps this can be achieved with hiding the UIImageView?

What approach would you recommend?


Solution

  • UIStackView handles hiding / un-hiding views very well and lets the non-hidden elements take up any extra space. Would highly recommend using a UIStackView in this scenario. Custom spacing is no big deal, and can be accomplished like this:

    stackView.setCustomSpacing(6, after: UILabel2)