4

I need to evenly space X items, and the container for the items can have dynamic width, and I want the first and last items to stick to left and right edge:

|-0-[item1]-[...]-[itemX]-0-|

so that no matter how wide the container is, the items are always evenly spaced, how to implement this with layout constraints?

edit: I was thinking that if I can set item1 and item2 to have same spacing as item2 and item3 and so on, then this should be easy, but I don't think I can set it without a constant width?

hzxu
  • 5,753
  • 11
  • 60
  • 95
  • have you tried what you suggested in the last sentence? – Gabriele Petronella Sep 28 '13 at 06:06
  • possible duplicate of [Evenly space multiple views within a container view](http://stackoverflow.com/questions/13075415/evenly-space-multiple-views-within-a-container-view) – Gabriele Petronella Sep 28 '13 at 06:07
  • and http://stackoverflow.com/questions/13680303/ios-auto-layout-equal-spaces-to-fit-superviews-width – Gabriele Petronella Sep 28 '13 at 06:07
  • I think the other question closed as duplicate should not have been, because the referenced duplicate dealt with vertical not horizontal spacing. In which case, I believe that a satisfactory solution that uses Auto Layout rather than frames is still outstanding – Max MacLeod Sep 30 '13 at 09:30
  • I have a good solution to this using IB that I posted [here][1] [1]: http://stackoverflow.com/a/25898949/951349 – SmileBot Sep 23 '14 at 03:53

1 Answers1

9

You can't set spaces to have the same width but you can use "spacer" views.

Put an invisible view between all your views and you can set the format like this...

@"|[view1][spacer1][view2(==view1)][spacer2(==spacer1)]...[spacerN(==spacer1)][viewN]|"

This will make all the views have equal spaces between them.

Make sure to set the spacer views as alpha 0 or hidden or background color clear.

Fogmeister
  • 76,236
  • 42
  • 207
  • 306
  • The problem with this is that when the size of the container is changed, the size of the spacer need to be changed as well? – hzxu Sep 28 '13 at 07:51
  • No, this will work if the size of the container changes. All you are doing is saying that they are the same size as each other. You're not giving them a fixed size. This is why it works in the first place. – Fogmeister Sep 28 '13 at 08:03