iOS UIButton Introduction

Buttons are the most commonly used and simplest controls in iOS applications and are often used to respond to user actions. Generally we use UIButton class to implement the button. This section will focus on adding buttons, beautifying buttons, and how to implement button responses.

1. Use Code To Add Button.

To add a button to the main view in source code, you first need to instantiate a button object using the UIButton class, then set the location and size, and finally add the button object to the main view using the addSubview() method.

The following code adds a button object with orange background color to the main view.

import UIKit
class ViewController: UIViewController {
        override func viewDidLoad() {
            // Create UIButton object.
            let button=UIButton(frame: CGRect(x: 143, y: 241, width: 88, height: 30)) 

            // Add UIButton object.

When you run the program, you can see below picture.

add button in source code screen

2. Beautify The Button.

Beautify a button is simply setting the properties of the button. There are two ways to set the button properties. One way is to use the property inspector in the interface builder, the other way is to set it by source code. The following sections will focus on how to use code to set buttons properties.

2.1 Set Button Appearance.

You can setup button’s title, image, etc to change button appearance. Below lists some of the commonly used methods for setting button appearance.

  1. setBackgroundImage : Sets the background image of the button.
  2. setImage : Set button image.
  3. setTitle : Set button title.
  4. setTitleColor : Set button title color.
  5. setTitleShadowColor : Set button title shadow color.

Below code will add a button to the main view. The title of this button is ‘Click Me’ and the color of the title is black.

import UIKit
class ViewController: UIViewController {
        override func viewDidLoad() {
        // Create button.
        let button=UIButton(frame: CGRect(x: 135, y: 241, width: 97, height: 30)) 
        // Set button title.
        button.setTitle("Click Me", for: UIControlState.normal) 
        // Set button title color.
        button.setTitleColor (, for: UIControlState.normal) 
        // Add button to the main view.

2.2 Set Button State.

When setting the title and color of the button, the state of the button also needs to be set. Button state indicating what the title and title color of the button will look like in a certain state. For example, UIControlState.normal represents normal state of a button. For a view like a button that can accept user input is also called a control. These controls all have their own state. Below is the control state list.

  1. normal : normal state.
  2. highlighted : highlight state.
  3. disabled : disable state and do not accept any events.
  4. selected : selected state.
  5. application : application flags.

2.3 Set Button Type.

There are various types of buttons. For example, in the address book, the button to add a new contact is a plus, while the button to see the details of the call is an exclamation point, etc. All these button types can be implemented using UIButtonType when instantiating the button object. Below is the UIButtonType list.

  1. system : System default style button.
  2. custom : Custom style button.
  3. detailDisclosure : Blue exclamation point button, mainly used for detail description.
  4. infoLight : Bright color exclamation point.
  5. infoDark : Dark exclamation point.
  6. contactAdd : The cross plus button, which is usually used as add contact entry.

The following code adds two different styles of buttons to the main view.

import UIKit
class ViewController: UIViewController {
        override func viewDidLoad() {

        // Add first button with contactAdd type.
        let button1=UIButton(type: UIButtonType.contactAdd) 190, y: 250) 

        // Add second button with detailDisclosure type.
        let button2=UIButton(type: UIButtonType.detailDisclosure) 190, y: 450) 

When you run the program, you can see below effect.

contact add and detail disclosure type button

3. Add Button Response.

There are two methods to add button response code, one is through interface builder, the other is through source code.

3.1 Use interface builder to add button response code.

Add a button using the interface builder can use drag and drop to implement the button response code, which is also the simplest way to implement response.

The following will implement tap button to change main view background color effect.

  1. Open the Main.storyboard file, drag the button control from the view library to the main view, and set the title to “Tap me, Change View Color”.
  2. Click the Show the Assistant editor button to adjust the Xcode interface builder to the effect shown in below picture.
    add button response in interface builder
  3. Hold down the Ctrl key and drag the button object in the interface, and a blue line appears, dragging the blue line to the white space of the ViewController.swift file.
    press ctrl key and drag the button to viewcontroller.swift file at the same time
  4. When you release the mouse, a dialog box that declares the associated socket variable will pop up.
    declares the associated socket variable popup dialog
  5. Set the Connection option to Action indicate that an Action is associated. Set the Name to tapButton, indicate that the associated action is named tapButton, you can specify any name here.
    set connection to action and add action name
  6. Click the Connect button and you’ll see the code in the ViewController.swift file. Now a method called tapButton() will be triggered when the user taps the button.
    button response method
  7. Note: above method bind the action declaration and  UI object association at same time, and there is also another way to declare the action before it is associated. To declare action method you can use the keyword IBAction. This keyword tells the Main.storyboard that this method is an operation method and can be triggered by a control.
  8. After declaring an action, a small hollow circle appears in front of the code, indicating that the action has not been associated.
    declare ibaction method first
  9. After the action is declared, the association can be made. First, use the tool in the adjustment window to adjust the interface builder. Then, hold down the Ctrl key and drag the button object in the interface, and a blue line appears, associating the blue line with the action in the file ViewController.swift.
    associate button control with action method
  10. Finally, when the mouse is released, the button object is associated with the action method. At this point, the hollow circle in front of the action becomes to a solid circle, which indicates that the action has been associated.
  11. Open the ViewController.swift file and write the code that will implement the button response.
    import UIKit
    class ViewController: UIViewController {
        var isYellow:Bool=false
        @IBAction func tapButton(_ sender: AnyObject){

3.2 Use code to add button response.

To add response method to button that is created in source code, you need to use the addTarget (action:for:) method. The syntax is as follows.

func addTarget(_ target: AnyObject?, action: Selector, for controlEvents: UIControlEvents)

  1. target : Represents the target object. It is the sender of the action message.
  2. action : Represents a selector used to identify action method. It must not be empty.
  3. controlEvents : Represents control events that trigger the action method.

There are 19 control events in iOS.

  1. touchDown : Single touch press event: when a user touches the screen, or when a new finger drops.
  2. touchDownRepeat : Multi-touch press event, the touch count is greater than 1: when the user presses the second, third, or fourth finger.
  3. touchDragInside : When a touch is dragged inside the control window.
  4. touchDragOutside : When a touch is dragged outside the control window.
  5. touchDragEnter : When a touch is dragged from the control window outside to inside.
  6. touchDragExit : When a touch is dragged from the inside of the control window to the outside.
  7. touchUpInside : All touch lift events within the control.
  8. touchUpOutside : All touch lift events outside the control.
  9. touchCancel : All touch cancellation events, such as when a touch is cancelled due to place too many fingers on the screen, or is interrupted by a lock or a phone call.
  10. valueChanged : Send notifications when the value of the control changes. Used for controls like sliders, segmented controls etc. Developers can configure when the slider control sends notifications.
  11. editingDidBegin : Send notifications when editing begins in a text control.
  12. editingChanged : Send notifications when text in a text control is changed.
  13. editingDidEnd : Send notifications when editing in a text control is finished.
  14. editingDidEndOnExit : A notification is sent when editing in a text control ends by pressing the enter key (or equivalent action).
  15. allTouchEvents : Notifies all touch events.
  16. allEditingEvents : Notifies all events about text editing.
  17. applicationReserved : Application reserved events.
  18. systemReserved : All the system reserved events.
  19. AllEvents : Contains all events.

Below code will change the main view background color when tap the button.

import UIKit
class ViewController: UIViewController {
        var isCyan:Bool=false

        override func viewDidLoad() {

            let button=UIButton(frame: CGRect(x: 90, y: 545, width: 225, height: 30))

            button.setTitle("Tap me,Change View Color", for: UIControlState())

            button.setTitleColor (, for: UIControlState())


            button.addTarget(self, action:#selector(UIViewController.tapbutton), for:UIControlEvents.touchUpInside)

        @objc func tapbutton(){

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.