How to align two buttons equidistant from the center of a UIView

I work with auto-layout. Facing on an interesting issue. Fortunately, I overcame it for a while, but he needs to know how to best solve it.

enter image description here

Problem: As shown in the picture above, I have several buttons. Both of them should have been placed at the same width from the center of the UIView (the bold vertical line is the center point of view). Also I have to apply to the restriction so that the distance between the buttons is automatically adjusted. eg. the distance should be 25% of the width of the device. If my device width is 320, the distance between the buttons is 80 pixels and so on.

Solution (I tried): For the above problem, I tried to solve the problem. As shown in the figure, I added on the dummy view in UIView, the width of the dummy is equal to the interval between the two buttons. And then I applied the constraints to the dummy view. for example: 1. Horizontal centre of the UIView 2.Width equals to the UIView width with 0.25 as a multiplier

Question: The above solution works fine for me. But if in the future, if there are too many complex elements in my view, adding a dummy view might not be a good idea. So, is there any other clean way to do this?

+6
source share
3 answers

I ran into the same problem. I decided to use the idea derived from rdelmar's answer.

This is what I did.

For the left button:

  • Added restriction to "Center - Horizontally in the container"
  • Then the factor changed by 0.5 instead of 1 for this restriction.

For the right button:

  • Added restriction to "Center - Horizontally in the container"
  • Then, for this restriction, the factor changed by 1.5 instead of 1.

Let me know if this worked for you.

+15
source

You can do this in a storyboard (or xib) using restrictions on the right edge of the screen - the value of the right edge is the same as the width of the screen, so you can use it for calculations. For the left button, you want its back edge to be equal to the right edge of the supervisor, equal to 0.375 (0.5 minus 0.125, which is half your 25% requirement). the right button will have a leading edge equal to the right edge of the supervisor time 0.625 (.5 +.125).

The restrictions are as follows:

enter image description here

enter image description here

+1
source

try aligning the leading edge of your btn2 and the falling edge of your btn1 with the center y of your view, set by a constant at 0 and a factor of 200: 160 and 120: 160 respectively, where your center y is the second element

0
source

Source: https://habr.com/ru/post/983022/


All Articles