'Swift: Algorithm to build stackviews based on contents of a List

This shouldn't be too hard, but I am too dumb to find the solution.

I have a View in which I want to display a vertical UIStackview, which carries multiple horizontal stack views, each of them carrying three buttons. The List of Buttons however is not fixed and the stack view has to be able to adapt.

I need to have a loop that goes through the list and adds it to an existing horizontal stack if there is less than 3 buttons inside of it or creates a new horizontal stack view, adds that stack view to the vertical stack view, and finally, adds the button to that horizontal stack.

How would I go about doing that?



Solution 1:[1]

You may find it much easier to work out your code if you write out in plain language what you're trying to do.

So, start with:

  • get a list of button titles (an array of strings)
  • create a vertical stack view
  • run a loop until we're out of button titles
  • inside the loop, create a horizontal stack view
  • add it to the vertical stack view
  • add up to 3 buttons to it

Then, start filling in partial code...

    // list of button titles
    let btnList: [String] = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"]
    
    // create vertical stack view
    print("New vStack")
    
    // array index var
    var idx: Int = 0
    
    while idx < btnList.count {
        // create horizontal stack view and
        // add it to vertical stack view
        print("New hStack - add to vertical stack view")
        for _ in 1...3 {
            if idx < btnList.count {
                let nextTitle = btnList[idx]
                // create a new button with title
                // add it to the horizontal stack view
                print("add button \(nextTitle) to hStack")
                // increment the array index
                idx += 1
            }
        }
    }

If you run that, you'll see this in the debug console:

New vStack
New hStack - add to vertical stack view
add button A to hStack
add button B to hStack
add button C to hStack
New hStack - add to vertical stack view
add button D to hStack
add button E to hStack
add button F to hStack
New hStack - add to vertical stack view
add button G to hStack
add button H to hStack
add button I to hStack
New hStack - add to vertical stack view
add button J to hStack
done

At this point, all you need to do is change the print() statements to the actual code needed for each step.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 DonMag