2

I'm stuck with a problem I'm sure one of you guys can help me with. I'm developing an iOS-Application with Swift3 and what I'm trying to create is something like this:

Screenshot1
Screenshot2

The screenshots show just a part of my UIViewcontroller. The remaining space is filled with other views that are not part of the question. As you can see the size and position of my subviews(the icon) depends on the amount of icons i'm given (not more than 8). If more than 5 icons exist it should create a second row and decrease the size of the icons to fit the space. My views should always be centered meaning they are evenly distributd to the left and right.

What i tried so far:

  • I created a horizontal StackView and tried to fill it programmatically but that did not solve the problem for more than 5 Views.
  • Tried setting up some views with auto-layout constraints but could not solve the problem of different sizes and positioning.

Of course I could do everything in code. Creating and placing all Views one by one but I would like to find a cleaner solution.

Thanks for you answers. Feedback is appreciated.

  • Collection view can be better option over there !! – Prashant Tukadiya Feb 01 '17 at 09:34
  • Hello Mike, thank you for you answer. I've used CollectionViews already but only with fixed size cells. Do you know how i can center cells horizontally inside a collection view? I could controll the view size with the 'sizeForItemAt function', right? – Albert.Hildenberg Feb 01 '17 at 09:42
  • center cells horizontally , It all depends on the height of collection view, what you need to do is set height of collection view according to number of rows are there, ie let sayf 5 cell , then set height 120 if more than that set double like 240, distribute height equally amon cells, will help – Prashant Tukadiya Feb 01 '17 at 12:04

3 Answers3

0

UICollectionView Can be a better option here.

Shuja
  • 113
  • 7
0

Its either UIStackView or UICollectionView since they both handle the distribution of subview. Since you have a max of 8 icons I'd just use UIStackView and vertically stack two horizontal stackViews. You put items 1-5 in stackview 1 and 6-8 in stackview 2. If you need the two rows to have the same distribution then you need to put empty views with horizontal constraints equal to the imageView width to make the second stackview have as many items as the first when the number is odd.

Josh Homann
  • 15,933
  • 3
  • 30
  • 33
0

Thanks to Shuja and Josh for leading me in the right direction.

I ended up using a UICollectionView and changing some values inside sizeForItemAt to respond to changing cell sizes and insetForSectionAt functions to center my cells horizontally.