Lasse Kristensen
Lasse Kristensen

Reputation: 149

for loop to change buttons titles in Swift

I'd like to use a for loop to change the title of 5 buttons. I'd like to use i as the variable to replace the number.

for (var i = 1; i < 6; ++i) {     

let buttonName = button0 + i                  
buttonName.setTitle("Sydvestpynten", forState: UIControlState.Normal)

}

My buttons are called button01, button02, etc.

The above code doesn't work. What am I doing wrong?

Upvotes: 2

Views: 3390

Answers (3)

DarkDust
DarkDust

Reputation: 92306

You cannot create variable names on the fly like you're trying to do. Things like that only work in a few (scripting) languages and even then are considered to be a bad practice.

But there's an easy workaround: use an array. Either store your buttons in an array instead of creating a lot of variables or construct your array on the fly:

for button in [button01, button02, button03, button04, button05, button05] {
    button.setTitle("Sydvestpynten", forState: UIControlState.Normal)
}

If you're using Interface Builder, remember that you can also use IBOutletCollections with Swift. The syntax is a bit different, though:

@IBOutlet var buttons: Array<UIButton>

In Interface Builder, you can then assign several buttons to the same outlet (buttons).

Upvotes: 4

Daniel T.
Daniel T.

Reputation: 33967

let buttons = [button01, button02, button03...]
for button in buttons {
    button.setTitle("Sydvestpynten", forState: .Normal)
}

It would probably be a good idea to make the array a property.

Upvotes: 2

Rajeev Bhatia
Rajeev Bhatia

Reputation: 2994

Try storing your buttons in an array and then looping through the array and setting the titles instead.

var arrayOfButtons:[UIButton] = []

//add buttons here using arrayOfButtons.append(myButton)

for button in arrayOfButtons
{
    button.setTitle("title", forState: UIControlState.Normal)
}

Upvotes: 0

Related Questions