Generating UIButtons from a loop

This is a very useful technique and it’s pretty straight forward.
Let’s say we have an array of items or heroes and we want to dynamically create buttons that
will do something linked to the hero/item selected.
One example is if you have an array of saved games and you want to generate buttons to load each saved game.
In reality you’ll most likely be generating your array from dynamic content – plist or CoreData.

In our case, just for the sake of this example we’ll start off by creating a static array with some Strings:

Now we have our array to work with. Let’s generate some UIButtons:

First problem you are going to encounter here is that your buttons will overlap over each other, so you can only see one button on the screen ( the last one to add ):

Screen Shot 2015-01-28 at 1.15.44 PM
so we need to add an offset. So we’ll end up with this:

So at this point we should have all of our buttons generated.
You should see something like this:
Screen Shot 2015-01-28 at 1.17.10 PM
All good except nothing happens when you press them..wait !
Did I say nothing ? I meant this:
Screen Shot 2015-01-28 at 1.17.23 PM

Screen Shot 2015-01-28 at 1.17.28 PM

Here is the fix for that..we are going to create a function for the button taps:

You can also pass let’s say the UIButton’s tag instead.
If you only need Int’s you can use sender.tag, instead of the titleLabel.text .

Keep in mind that for this example you would put the generator for the Buttons in the viewDidLoad()

method ( or enclose it in a function and then call that function in viewDidLoad()  ), but the “villainButtonPressed function you will place outside of viewDidLoad.

And Voila, you should now have your dynamically generated UIButtons!

I’ve added a few more things, just so we can get some system messages, to make sure we have not gone completely crazy:

Screen Shot 2015-01-28 at 1.24.15 PM
Here is what your full code should look like:

Here is an addition on request. This will generate one button at the start and a new button on button click:

Here is a link to the second part: UIButtons From A loop – part 2