Search code examples
iosswiftxcodeautolayoutconstraints

Percentage constraint width


I have a view with a width value of 700. I also place several buttons and an image inside this view. The problem is exactly that I asked them the width and when the device changed to a device with a large screen, these objects did not stretch as needed.

Then I read that you can set the width as a percentage so that the interface is good. My button whose width value was = 32. I made the width equivalent to view and set the factor to 0.32. But the result has not changed, and in appearance the button has become even smaller.

How can I set the percentage width correctly so that the button automatically resizes to fit the size of this view ??


Solution

  • You want to set the multiplier relative to the superview.

    So, if you have originally designed your button to be 32-pts wide, and its superview (the view it is embedded in) is 700-pts wide, your button width should be equal to the superview width with a multiplier of 32:700

    Here is an example -- I'm starting with button width of 32 and view width of 300 to make it easier to see the "stretching".

    The button width constraint is:

    Proportional Width to: Superview
    Multiplier: 32:300
    

    enter image description here

    So, when I change the width of the superview to 400, 500, 600, 700, you can see that the button stretches while remain proportional:

    enter image description here