Search code examples
for-loopswift3nested-loopsiboutletcollection

Nested for loops in swift 3 for uibuttons title


I have an outlet collection of UIButtons:

@IBOutlet var categoriesButtonLabels: [UIButton]!

each button has a different tag (set in the storyboard).

I want to change their titles filling with an array of strings (the categories which I retrieve somewhere else in my code from my FireBase database).

I tried something like this:

override func viewDidLoad() {
    super.viewDidLoad()
// Setting Category buttons labels
    for button in categoriesButtonLabels {
        for i in categories {
            button.setTitle("\(i)", for: .normal)
        }
    }
}

but it's getting just the last value of the categories array and setting the title the same for all the buttons... What am I doing wrong?

For the sake of completeness: This is my category array:

for (index, value) in categories.enumerated() {
print("\(index) = \(value)")
}

and outlet collection:

for (index, value) in categoriesButtonLabels.enumerated() {
print("\(index) = \(value)")
}

Output:

categories string array is:0 = sports categories string array is:1 = science categories string array is:2 = movies categories string array is:3 = music categories string array is:4 = history

Outlet UIButtons Collection is:0 = > Outlet UIButtons Collection is:1 = > Outlet UIButtons Collection is:2 = > Outlet UIButtons Collection is:3 = > Outlet UIButtons Collection is:4 = >


Solution

  • Remove the inner loop:

    for (i, button) in categoriesButtonLabels.enumerated() {
        button.setTitle("\(categories[i])", for: .normal)
    }