Search code examples
iosswiftxibxcode-storyboard

Resizing issues with xib while adding constraints


I am new to this and kind of stuck in understanding how to resolve it.

I have a view (freeform) created in xib and I want to add constraints to the view based on the sizes.

enter image description here

Each of the button is inside a view. I want to add the constraints for all of them such that based on the screen size they automatically resize. When I try to "Add missing Constraints" it just messes up the whole view. Can anyone help me understand how the resizing works when we would have to divide the screen such that 3 views are equally divided. ( 3 on the top half and 3 on the bottom half)

Thanks in advance.


Solution

  • This approach allows you to create a dynamically resizable xib with a set amount of subviews/buttons.

    Since you mention "Add missing constraints" I will assume you're using AuotLayout. First of all, I recommend you to not use "Add missing constraints" as it's very unpredictable, and you'll rarely receive the result you want.

    To add a Static amount of buttons to a xib I would do the following:

    1. Select all the Buttons in each row
    2. Choose the "Embed In" option (in the lower right corner) and pick "Stack View", your views will resize but they're now added to a dynamically resizing UIStackView. enter image description here
    3. Now do the same with the second row of buttons.
    4. Select each Stack View and make sure they have their Distribution option set to "Fill Equally" to give each button the same size. enter image description here
    5. Now select both Stack Views, and yet again add them both to a Stack View. This Stack View also needs its Distribution set to "Fill Equally". enter image description here
    6. You may now add your own constraints. Select the "Add New Constraints" option to manually add them. They may be whatever you desire, I set mine to 20px from each side. enter image description here
    7. You should now have a dynamically resizing Button XIB with a Static amount of Buttons!