Reshad
Reshad

Reputation: 2652

create a UIButton for each object in array

Hello guys I want to create a UIButton programmatically from every object in an array. something like

for answer in answers { 
  //create button
}

But how do I assign all these buttons a randomized and unique variable?

like var randomvar = UIButton() ?

Upvotes: 0

Views: 1582

Answers (3)

Arbitur
Arbitur

Reputation: 39091

I had this problem when I was new to OOP x).

Basically a variable when handling an object is just a pointer to the address in memory.

An array with objects will actually be an array with pointers to all unique objects, in your case these objects are UIButton's.

So in your for-loop you have to add those buttons inside another array.

var buttons = [UIButton]()

for answer in answers {
    let btn = UIButton()
    ...
    buttons.append(btn)
}

Then you can access each unique button by accessing them trough buttons.

buttons[2].setTitle("test 2", forControlEvent: .Normal)

Upvotes: 3

Joris Kluivers
Joris Kluivers

Reputation: 12081

Loop over your array and create the button for each item. Either add it to your view directly or save it into an array for later access

var buttons = [UIButton]()

for answers in answer {
    let button = UIButton(...)
    button.addTarget(self, action: "buttonAction:", forControlEvents: . TouchUpInside)

    // add to a view
    button.frame = ...
    view.addSubview(button)

    // or save for later use
    buttons.append(button)
}

Upvotes: 2

Greg
Greg

Reputation: 25459

The better approach is to create an array property:

var array: [UIButton]?

and inside the loop create a button and add it to this array.

If you need to access any button you can access it by index.

Upvotes: 1

Related Questions