da1lbi3
da1lbi3

Reputation: 4519

How to loop through buttons

I have 16 buttons named like btn1, btn2 etc.. how can i loop through this and set an value to each button?

I have this code:

  //set values on the button
        for i in 1..<17{

            var mybutton = "btn" + String(i);
            println(mybutton)
            mybutton.setTitle(String(number), forState: UIControlState.Normal)
        }

    }

but that doesn't work because the software sees it as an string...

How can i solve this issue?

Upvotes: 0

Views: 1251

Answers (3)

Gwendle
Gwendle

Reputation: 1941

If you added these in the interface builder and have a reference to the superview, you can assign each of them a tag from 1 to 16 access them using the method "viewWithTag":

//set values on the button
        for i in 1..<17{
            var sView = [REFERENCE TO YOUR SUPERVIEW HERE]
            var mybutton = sView.viewWithTag(i) as! UIButton?
            println(mybutton)
            mybutton.setTitle(String(number), forState: UIControlState.Normal)
        }

    }

Upvotes: 0

Eendje
Eendje

Reputation: 8883

In addition to the answer of ChikabuZ:

If you separately added the buttons in storyboard, I suggest you to create an outlet collection instead: @IBOutlet var buttons: [UIButton]!.
CTRL drag all those buttons in this outlet and you can access the array like ChikabuZ has suggested.

I personally prefer to use a map instead:

buttons.map { $0.setTitle(String(number), forState: .Normal) }

Upvotes: 0

ChikabuZ
ChikabuZ

Reputation: 10205

You can create array of buttons:

let array = [btn1, btn2, btn3 ...]

for i in array.count
{
   //do something 
   array[i].setTitle(String(number), forState: UIControlState.Normal)
}

But if you have a lot of buttons in Interface Builder, the better way to create them programmatically.

Upvotes: 2

Related Questions