Search code examples
iosxcodeuibuttonnslayoutconstraint

How do I make elements a percentage width in Xcode


I am new to Xcode, previously developed apps as hybrid so decided to learn swift. The language itself is easy to learn, I code in many languages. But I am not understanding why Xcode doesn't let me use percentage widths on things!

The first screenshot shows 4 buttons next to each other on iPhone 8 plus, but the second screenshot is when I change to iPad, you can see that the boxes don't resize to fit.

It doesn't allow me to enter percentage (25%) of the view so how am I supposed to make them all fit on difference devices? I know about constraints but I can't figure out what constrains it needs to a) Make them all stay 25% of the view b) So they sit next to each other and just resize.

enter image description here

enter image description here

After trying the accepted answer it worked, but when I try to add a second row doing the same thing the following happens:

Setting constraints for first row:

enter image description here

Setting constraints for second row:

enter image description here

The result:

enter image description here

Why did it work for the first row but not the second?


Solution

  • Add all buttons in a single container view. Assign equal width constraint to all button with no spacing with each other (adjacent view/button) and superview.

    Try this and see:

    enter image description here


    Here is result in iPhone 4s and 8+ preview:

    enter image description here


    Result for iPad:

    enter image description here