Adding UIButtons in a UIView with dynamic width in swift

4137 views ios

I am trying to add UIButtons in a UIView, buttons width will change depending on their title. So it could be one button in a row or 3 buttons in a row. If there is no space in same row button should be added in the next row. Something like this enter image description here

and UIView height should increase if more lines are added up-to a certain height.

I am thinking to start with UIStackViews but not sure how to achieve this functionality. Any help is appreciated.

answered question

UICollectionView is made for this type of layout.

1 Answer


A UICollectionView using a UICollectionViewFlowLayout would do this by default. The only thing you would have to do is update the height of the collevtionView to match its content size if you don't want it to certainly scroll.

Using a UIStackView would require you to calculate the the size of every button and move down to a new row when they don't fit. While that doesn't sound to hard, it's a lot of layout math you'll have to do.

posted this

Have an answer?


Please login first before posting an answer.