Dynamic UIButton on UIScrollView Swift 3.0

The following code snippet shows how to create dynamic UIbutton in UIScrollView using Swift 3.0.

Before we begin, let us create a new project by selecting Single View Application template and provide ProjectName, Team, Organization Name, Organization Identifier, Bundle Identifier details.

Open Main.storyboard file, drag and drop UIScrollview from the object library.
Add the AutoLayout constraints for UIScrollView by selecting ScrollView and clicking on Add New Alignment Constraints pin and checking Horizontal in Container and Vertically in Container click on Add Constraints.

Create Outlet for the scroll view by opening Assistant Editor(⌘ + ⌥ + return) holding control drag and drop form Scrollview to the ViewController.Swift file above viewDidLoad method and name it as mScrollView.

Let us now open ViewController.swift and create a new function by name dynamicButtonCreation.

Initially let’s set isScrollEnabled , isUserInteractionEnabled properties to true and let’s set the number of buttons and number of rows which has to be displayed in our case we have 16 buttons which are displayed in 2 rows. Let’s divide numberOfButtons into 2 and equally spread the buttons in 2 rows as shown in below snippet. let’s create a button programmatically and set the frame, tag values, title and addTarget(Button Action) for each of the buttons as shown below.

I am a self-driven software professional from Bangalore who live with a desire to set new examples, something that can create a unique signature of my own. I am a very friendly, fun loving person. I love to interact with people and make new friends who can bring difference in my life. I strive to become a better programmer.