iosxcodestoryboarduistackview

How can I arrange calculator buttons in a grid layout within the Xcode15 user interface


I've created a StackView in Xcode 15 using ViewController to arrange the calculator buttons in a grid, but I'm encountering an issue where the button sizes automatically shrink. This prevents me from evenly distributing them horizontally.

I learned from a tutorial site that setting the Distribution to 'Fill Equally' would allow for equal spacing. I tried it, but as shown in the image, the buttons ended up shrinking. (Note: I haven't set any constraints.) (Note: I've attached images of both the intended final layout and the current state.)

Is there any additional setup required to arrange the buttons neatly? I'd appreciate it if you could suggest a solution that doesn't involve using Swift code!

What I want to do:

The image is what I want to do!

The result:

The image below shows the state where each button ends up shrinking.


Solution

  • To get your started...

    Begin by adding your top "display" label, constraining Top/Leading/Trailing:

    enter image description here

    Next, add the first "row" of 4 buttons like this - exact size/placement doesn't matter:

    enter image description here

    Select the 4 buttons and embed in a stack view (horizontal):

    enter image description here

    You see that they "shrink" ... that's because a UIStackView arranges its subviews based on their Intrinsic sizes. Since we haven't done anything specific with sizes yet, that's what we get.

    So the next step is to create four more "button rows" -- we can use copy/paste or duplicate -- and embed the five button rows in a Vertical stack view:

    enter image description here

    Note: for the time being, we're using two "0" buttons on the bottom row... we'll fix that as the last step.

    Select each "row" stack view and set these properties:

    enter image description here

    Select the vertical stack view holding the rows and set these properties:

    enter image description here

    Now, constrain that vertical stack view to fill the view:

    enter image description here

    and... we now have this layout:

    enter image description here

    Let's give the "display label" a Height constraint so it has a little top/bottom padding:

    enter image description here

    and then we can set the view and label background colors to Black:

    enter image description here

    The bottom "row" is not 4-buttons, so we need to fix that.

    and we get this:

    enter image description here

    Give that a try... if you run into trouble, here is the source for that Storyboard, so you can inspect it: https://pastebin.com/BKQgSr9g