How to align two buttons equidistance from the centre of the UIView

戏子无情 提交于 2019-12-31 22:38:41

问题


I am working with auto layout . Facing on interesting issue . Fortunately overcame from it for the time but need to know the best way to solve it .

Problem : As showing in the above figure I have couple of buttons . Both needed to place at equidistance width from the centre of the UIView (bold vertical line is centre of the view). Also I have to apply to constraint in such a way that distance between the button will be automatically adjusted. for e.g. the distance should be 25% of the device width. If my device width is 320 the distance between the button is 80 pixels and so on.

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

Question: above solution is working perfectly for me . But if in future if my view will have too many complex elements then adding dummy view might not be the good idea . So, Is there any other clean way to do this ?


回答1:


I faced the same problem. I resolved using the idea i got from rdelmar's answer.

This is what I did.

For left button:

  1. Added the constraint to 'Center - Horizontally in container'
  2. Then changed the multiplier to 0.5 instead of 1 for that constraint.

For right button:

  1. Added the constraint to 'Center - Horizontally in container'
  2. Then changed the multiplier to 1.5 instead of 1 for that constraint.

Let me know if it worked for you.




回答2:


You can do this in the storyboard (or xib) by using constraints to 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 that for calculations. For the left button you want its trailing edge to equal the superview's right edge times 0.375 (0.5 minus .125 which is half of your 25% requirement). the right button would have its leading edge equal to right edge of superview times 0.625 (.5 + .125).

The constraints look like this,




回答3:


try Aligning leading edge of your btn2 and trailing edge of your btn1 with center y of your view set constant to 0 and multiplier 200:160 and 120:160 respectively where your center y is second item



来源:https://stackoverflow.com/questions/28735399/how-to-align-two-buttons-equidistance-from-the-centre-of-the-uiview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!