How To Create Multiple Button And Add Button Action Function Programmatically In iOS Swift

We have learned how to add the button to the iOS app and how to add a button click event process function in the article iOS Add Click Event To UIButton Swift Example. But in that article, we add a button from the Xcode UI component library by drag & drop, we add a button click event process function by drag & drop to add a connection between UI component and source code also. But sometimes we need to create the button and add the button event process function programmatically purely in Swift source code. This article will tell you how to do it.

1. How To Create Button In Swift Source Code.

1.1 Create Button.

  1. You can use swift UIKit.UIButton class to create a button in source code as below.
  2. You should provide a button type parameter to UIButton class initializer to tell iOS which type of button do you want to create.
    let btn = UIButton(type: UIButton.ButtonType.system)

1.2 Set Button Location And Size.

  1. After you create the UIButton object, you should set it’s frame property to a CGRect object to set the button’s x, y location, and width, height value.
    btn.frame = CGRect(x: 10, y: 100, width: 100, height: 100)

1.3 Set Button Background Color.

  1. If you want to change the button background color, you need to set UIButton‘s backgroundColor property to a UIColor object like below.
  2. The below code will set the button background color to light gray.
    btn.backgroundColor = UIColor.lightGray

1.4 Set Button Text And Text Color.

  1. To set button text, you need to call UIButton‘s setTitle method, this method has two parameters, the first one is the text, the second one is the button state, so the text will be shown only when the button is in the state that the second parameter provided.
  2. In the below example, the button will display the text “Hello swift button” when it is in the normal state.
    btn.setTitle("Hello swift button.", for: UIControl.State.normal)
  3. Each button can have four states, UIControl.State.normal, UIControl.State.selected, UIControl.State.highlighted, UIControl.State.disabled, you can display different text for the button when the button is in a different state.
  4. In the below example, when the button is disabled, the button text will be changed to “Button one is disabled”.
    btn.setTitle("Button one is disabled.", for: UIControl.State.disabled)
  5. You can also set button text color by calling the UIButton object’s setTitleColor method as below code. The setTitleColor method has two parameters also, the first parameter is a UIColor instance, the second parameter is the button state.
  6. So in the below example code, when the button is in the disabled state, the button text will have a yellow color.
    btn.setTitleColor(UIColor.yellow, for: UIControl.State.disabled)

1.5 Set Button Text Font And Text Line Number.

  1. UIButton class’s titleLabel property can be used to set button text font and number of text lines.
  2. The titleLabel property has font and numberOfLines property.
  3. If you want to learn more about text font and the number of lines, please read the article How To Customize Swift Label Text Font And Set Text Shadow.
    // Set button text font to system bold.
    btn.titleLabel?.font = UIFont.boldSystemFont(ofSize: 25)
            
    // Set button text number of lines, 0 means no lines number limit.
    btn.titleLabel?.numberOfLines = 0

2. How To Add Function To Response Button Action Event In Swift Source Code.

  1. First you should define a function in your Xcode ViewController class, and apply the @objc attribute to the start of the function definition.
    @objc 
    func clickButtonTwo(){
        ......
    }
  2. Then call the UIButton object’s addTarget method to connect the button event with above function. So that when the event happened on the button, above function will be invoked. The addTarget method has three parameters, the first parameter is the object that define the event process function, the second parameter is a function name selector, the third parameter is an event name. In below example code, when the touchUpInside event happened on the button, it will invoke current object’s ( ViewController object ) clickButtonThree function.
    btn.addTarget(self, action: #selector(clickButtonThree), for: UIControl.Event.touchUpInside)

3. Create Button And Process Button Event Programmatically Example.

If you can not watch the above video, you can watch it on the youtube URL https://youtu.be/gS3BWubvBxc.

  1. There are three button in this example, the first button is used to demonstrate how to set different button properties.
  2. When you click the second or the third button, it will change the first button’s state, so you can see different button text.
  3. If you want to see the first button’s highlighted state text, just click the button for a while.

4. How To Create The Example Steps.

  1. Create a Xcode project, the Xcode project name is SwiftCreateButtonProgrammaticallyExample.
    create-button-and-button-event-process-function-programmatically-project-files-list
  2. You do not need to edit Main.storyboard file, what you need to do is edit ViewController.swift file with below source code.
    //
    //  ViewController.swift
    //  SwiftCreateButtonProgrammaticallyExample
    //
    //  Copyright © 2019 dev2qa.com. All rights reserved.
    //
    
    import UIKit
    
    class ViewController: UIViewController {
        
        var buttonOne:UIButton = UIButton()
        
        var buttonTwo:UIButton = UIButton()
        
        var buttonThree:UIButton = UIButton()
    
        override func viewDidLoad() {
            super.viewDidLoad()
            
            // Get screen width and height.
            let screenWidth = UIScreen.main.bounds.width
            let screenHeight = UIScreen.main.bounds.height
            
            
            createButtonOne(screenWidth: screenWidth, screenHeight: screenHeight)
            
            createButtonTwo(screenWidth: screenWidth, screenHeight: screenHeight)
            
            createButtonThree(screenWidth: screenWidth, screenHeight: screenHeight)
            
            // Add three button to main screen as subviews.
            self.view.addSubview(buttonOne)
            self.view.addSubview(buttonTwo)
            self.view.addSubview(buttonThree)
        }
        
        func createButtonOne(screenWidth:CGFloat, screenHeight:CGFloat){
            // Create a system default style UIButton object in swift source code.
            buttonOne = UIButton(type: UIButton.ButtonType.system)
            
            // Set UIButton x, y position, width and height.
            buttonOne.frame = CGRect(x: 10, y: screenHeight/2, width: screenWidth/2, height: 100)
            
            // Make the button locate at screen center.
            buttonOne.center = CGPoint(x: screenWidth/2, y: screenHeight/2)
            
            // Set button background color to light gray.
            buttonOne.backgroundColor = UIColor.lightGray
            
            // Set button text font.
            buttonOne.titleLabel?.font = UIFont.boldSystemFont(ofSize: 25)
            
            // Set button text number of lines, 0 means no lines number limit.
            buttonOne.titleLabel?.numberOfLines = 0
            
            // Set button normal state text and text color.
            buttonOne.setTitle("Create button in swift source code example.", for: UIControl.State.normal)
            buttonOne.setTitleColor(UIColor.red, for: UIControl.State.normal)
            
            // Set button selected state text and text color.
            buttonOne.setTitle("Button one is selected.", for: UIControl.State.selected)
            buttonOne.setTitleColor(UIColor.green, for: UIControl.State.selected)
            
            // Set button highlighted state text and text color.
            buttonOne.setTitle("Button one is highlighted.", for: UIControl.State.highlighted)
            buttonOne.setTitleColor(UIColor.blue, for: UIControl.State.highlighted)
            
            // Set button disabled state text and text color.
            buttonOne.setTitle("Button one is disabled.", for: UIControl.State.disabled)
            buttonOne.setTitleColor(UIColor.yellow, for: UIControl.State.disabled)
        }
        
        func createButtonTwo(screenWidth:CGFloat, screenHeight:CGFloat){
            // Create another system default style UIButton object, when click this button, it will disable buttonOne, when click this button again it will enable buttonOne.
            buttonTwo = UIButton(type: UIButton.ButtonType.system)
            
            buttonTwo.frame = CGRect(x: 0, y: screenHeight - 100, width: screenWidth, height: 50)
            buttonTwo.setTitle("Disable button one.", for: UIControl.State.normal)
            buttonTwo.setTitleColor(UIColor.red, for: UIControl.State.normal)
            buttonTwo.titleLabel?.font = UIFont.systemFont(ofSize: 25)
            buttonTwo.backgroundColor = UIColor.green
            
            // When buttonTwo occurred touchUpInside event then self.clickButtonTwo function will be invoked.
            buttonTwo.addTarget(self, action: #selector(clickButtonTwo), for: UIControl.Event.touchUpInside)
            
            // buttonTwo.addTarget(self, action: Selector("clickButtonTwo"), for: UIControl.Event.touchUpInside)
        }
        
        func createButtonThree(screenWidth:CGFloat, screenHeight:CGFloat){
            // Create another system default style UIButton object, when click this button, it will select buttonOne, when click this button again it will disselect buttonOne.
            buttonThree = UIButton(type: UIButton.ButtonType.system)
            
            buttonThree.frame = CGRect(x: 0, y: screenHeight - 50, width: screenWidth, height: 50)
            buttonThree.setTitle("Select button one.", for: UIControl.State.normal)
            buttonThree.setTitleColor(UIColor.red, for: UIControl.State.normal)
            buttonThree.titleLabel?.font = UIFont.systemFont(ofSize: 25)
            buttonThree.backgroundColor = UIColor.yellow
            
            // Associate button event with event process function.
            buttonThree.addTarget(self, action: #selector(clickButtonThree), for: UIControl.Event.touchUpInside)
        }
        
        /*
         This function will be invoked when click buttonTwo.
         */
        @objc
        func clickButtonTwo(){
            
            if(buttonOne.isEnabled)
            {
                buttonOne.isEnabled = false
                buttonTwo.setTitle("Enable button one", for: UIControl.State.normal)
            }else{
                buttonOne.isEnabled = true
                buttonTwo.setTitle("Disable button one", for: UIControl.State.normal)
            }
        }
        
        /*
         This function will be invoked when click buttonThree.
         */
        @objc
        func clickButtonThree(){
            
            if(buttonOne.isSelected)
            {
                buttonOne.isSelected = false
                buttonThree.setTitle("Select button one", for: UIControl.State.normal)
            }else{
                buttonOne.isSelected = true
                buttonThree.setTitle("Deselect button one", for: UIControl.State.normal)
            }
        }
    
    
    }
    
    

References

  1. How To Create A Swift Project In Xcode

1 thought on “How To Create Multiple Button And Add Button Action Function Programmatically In iOS Swift”

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.