0

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() ?

2
  • are you going to present those buttons stacked or at random locations? Commented Oct 9, 2015 at 11:48
  • Specific locations so a lot of modification should be done as well. Commented Oct 9, 2015 at 11:50

3 Answers 3

3

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)
Sign up to request clarification or add additional context in comments.

Comments

2

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)
}

Comments

1

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.

2 Comments

I thought of this myself, but How can I still modify the button if I use an array? I mean I won't have the index at that moment right?
Position inside your array is the index so you have one.. If you want you can use tag to save index to the button (button.tag = index) it let you modified the buttons, you could even bet button by tag from the view (not recommended and not needed in your example).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.