0

Ok, so I have an array of buttons that I size in width (with sizeToFit()) according to the text assigned to them - meaning a button with "StackOverflow" as its title would be longer than one with "Stack" as title.

I have a container UIView that is a set width and the height is calculated using (numRows of buttons * height of each button), so height is always correct.

I need to programmatically arrange these variable width buttons on the container view (no constraints, using math) so that none run over the right edge, meaning they more or less fill up the width of the container view exactly. I succeeded it putting all the buttons into 3 rows on the container view (not by width, just in array order) like this:

//cont = container view
func organizeHashBtns()
    {
        var numPerRow = Int(3)
        var numRows = Int(hashButtons.count/numPerRow)
        var rowsAdded = Int(0)

        //just in order at first
        while rowsAdded < numRows {
            var index = rowsAdded*numPerRow
            //self.addSubview(cont)

            for i in index...index+3
            {
                hashButtons[i].center = CGPoint(x: (cont.bounds.width/3) * CGFloat(i), y: cont.bounds.height/2)
                cont.addSubview(hashButtons[i])
            }

            rowsAdded+=1
        }
    }

However I cant figure out how to determine which order to arrange the buttons in based on their individual width and width of whole container. How can I do this? How can I group the longer buttons with the shorter ones so the rows full of buttons are all about the same width?

blue
  • 7,175
  • 16
  • 81
  • 179
  • 1
    Have you tried using a `UIStackView`? – brandonscript Aug 23 '17 at 19:46
  • StackView - good point. Probably this will be helpful for you. https://stackoverflow.com/questions/30728062/add-views-in-uistackview-programmatically There are examples for objective-c and swift. – DJ-Glock Aug 23 '17 at 20:35
  • @brandonscript I've tried stack view in the past but haven't had success specifying # rows of buttons. Can you provide an example as an answer? – blue Aug 25 '17 at 16:33

1 Answers1

0

UIStackView is actually a breeze to start using. I'm showing this as if you built it in Interface Builder, but you can easily replicate the same behaviour in code. The trick is in the nesting of vertical > horizontal views, and setting the content distribution to "Equal Spacing".

enter image description here

brandonscript
  • 68,675
  • 32
  • 163
  • 220