Search code examples
iosswiftuibuttonautolayoutconstraints

Resize UIButton inside StackView in Storyboard



I have started to learn Swift recently and have the following problem with an Auto layout:

Have

  • simple structure from the elements: 1 UILabel + 2 UIButtons inside a StackView and UIImage as a background outside StackView: Screenshot
  • StackView has 4 constraints (last 4 as on my Screenshot);
  • 2 UIButtons have fixed height;
  • background has 4 constraints (first 4 as on my Screenshot);

Goal

  • I want 2 UIButtons to have a fixed width (250 or 300 or any number). And when switching to landscape mode it wasn't be stretched on the whole StackView and have an accurate look like on Portrait mode: Stretched Buttons
  • Wherein I want UILabel to be stretched as it is now;
  • I want to set it using StoryBoard (without a code)

Problem

  • I tried to add a fixed width constraints to both UIButtons but it's doesn't work: Landscape after fixed width
  • I tried to put each UIButton into a UIView but wasn't successful

I would be very grateful if someone can help me to understand and fix this behaviour.
Thank you in advance!


Solution

  • I tried to add a fixed width constraints to both UIButtons but it's doesn't work

    You are on the right track! You just need to set the stack view's alignment to Center.

    Stack View "Alignment" set to "Center"

    Result:

    Buttons have fixed width and are centered