How to add UIButton programmatically in SWIFT

In iOS app development sometime we’ve to create Buttons programmatically or dynamically. Today, I’ll show you how to do this using SWIFT programming language.

Let’s create a new Single View iOS application in Xcode. Name the project “DynamicButton”. Select swift as programming language.

Now go to ViewController.swift. In ViewDidLoad method we’ll write some codes that will add one button to the screen automatically at run time.

Let’s create a new method createButton and write some codes inside the method that will do the magic:

Explanation:

First we initialize a button object and keep it in button variable.

Then we set title and color of title of it.

In the following line of code, we add position and size of the button.

Add the button to view.

Finally let’s call the createButton in viewDidLoad method.

Now if you run the project (cmd + R) you can see a button created. If you tap on the button, nothing will happen at this moment. To call a method when button is pressed, we can write:

Do not forget to add ‘:’ after action method name (i.e. buttonPressed:). In action parameter of .addTarget, you set the method name that should be called. Now write buttonPressed method.

The buttonPressed: method simply displays an alert view. Now run the project and view result.

iOS Simulator Screen Shot Feb 18, 2015, 3.20.49 PM

The whole ViewController.swift will look like this:

 

Still feeling tired? Click here to download the project.