How to add UIButton programmatically in SWIFT 4.0

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:


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:



One thought to “How to add UIButton programmatically in SWIFT 4.0”

  1. Hello, very nice tutorial!
    I have a question: is there a way to make a custom polygonal shape as the “button.frame” instead of a CGRect?
    By the “button.frame” I don’t mean the image displayed in the button, I really mean THE button (if I tap outside of my polygonal shape nothing should happen).

Leave a Reply