Create UIButton Programmatically in Swift

In this Swift code example, you will learn how to create a UIButton in Swift programmatically without using the storyboard or the interface builder.

This is going to be a short tutorial with a very simple code example, but it will contain a lot of useful details like:

  • Create UIButton programmatically in Swift,
  • Position UIButton on a view,
  • Add an action to UIButton, so that when it is tapped, your function is called,
  • Set UIButton Title for specific UIControlState,
  • Change UIButton background color,
  • Change UIButton foreground text color.

If you are interested in video lessons on how to write Unit tests and UI tests to test your Swift mobile app, check out this page: Unit Testing Swift Mobile App

Create UIButton Programmatically

To create a UIButton programmatically, you need to instantiate a UIButton object and assign it to a variable. You can use the UIButton initializer that takes a button type as a parameter. For example, to create a system button, you can use:

let button = UIButton(type: .system)

The button type determines the appearance and behavior of the button. You can choose from different types, such as .custom.detailDisclosure.infoLight.infoDark.contactAdd, etc.

Next, you need to set the frame of the button, which defines its position and size on the screen. You can use the CGRect initializer that takes four parameters: x, y, width, and height. For example, to create a button with a width of 150 and a height of 45, and place it at (50, 100) on the screen, you can use:

let xPostion: CGFloat = 50
let yPostion: CGFloat = 100
let buttonWidth: CGFloat = 150
let buttonHeight: CGFloat = 45

button.frame = CGRect(x: xPostion, y: yPostion, width: buttonWidth, height: buttonHeight)

The x and y parameters specify the origin of the button’s frame, relative to the top-left corner of the screen. The width and height parameters specify the size of the button.

Customize the Appearance of UIButton Programmatically

After creating the button, you can customize its appearance by setting its properties. For example, you can set the background color of the button using the backgroundColor property. You can use a predefined color, such as .lightGray, or create your own color using the UIColor initializer that takes red, green, blue, and alpha values. For example, to set the background color of the button to light gray, you can use:

button.backgroundColor = .lightGray

You can also set the title of the button for different states using the setTitle method. The states are defined by the UIControl.State enum, and they include .normal.highlighted.selected.disabled, etc. For example, to set the title of the button to “Tap me” for the normal state, you can use:

button.setTitle("Tap me", for: .normal)

You can also set the tint color of the button using the tintColor property. The tint color affects the color of the button’s title and image. For example, to set the tint color of the button to black, you can use:

button.tintColor = .black

Add Click Action to UIButton

To add a click action to the button, you need to use the addTarget method, which takes four parameters: target, action, controlEvents, and sender. The target is the object that will perform the action, which is usually self. The action is the selector of the method that will be called when the button is clicked. The controlEvents is the event that triggers the action, such as .touchUpInside. The sender is the object that sends the action, which is usually the button itself. For example, to add a click action to the button that will call a method named buttonAction, you can use:

button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)

The buttonAction method must have the same signature as the selector, which means it must take a UIButton parameter and return nothing. For example, the buttonAction method could look like this:

@objc func buttonAction(_ sender: UIButton) {
    print("Button tapped")
}

The @objc attribute is required to make the method compatible with Objective-C, since selectors are an Objective-C feature. The _ before the sender parameter means that the parameter name can be omitted when calling the method. The print statement will print a message to the console when the button is tapped.

Add UIButton to a View Programmatically

Finally, to add the button to a view programmatically, you need to use the addSubview method of the view. The view can be any UIView object, such as the main view of the view controller, or a subview of the main view. For example, to add the button to the main view of the view controller, you can use:

view.addSubview(button)

The view property of the view controller refers to the main view that contains all the subviews. The addSubview method will add the button as a subview of the view, and display it on the screen.

Complete Code Example

Now that you know how to create, position, customize and display UIButton, let’s have a look at the complete code example below. You can copy and paste it into your Xcode project, or run it in an online Swift playground. The code example contains all the steps and methods that I explained in the previous sections. You can also modify the code to experiment with different button types, properties, and actions.

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        let button = UIButton(type: .system)

        let xPostion: CGFloat = 50
        let yPostion: CGFloat = 100
        let buttonWidth: CGFloat = 150
        let buttonHeight: CGFloat = 45

        button.frame = CGRect(x: xPostion, y: yPostion, width: buttonWidth, height: buttonHeight)
        button.backgroundColor = .lightGray
        button.setTitle("Tap me", for: .normal)
        button.tintColor = .black
        button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)

        view.addSubview(button)
    }

    @objc func buttonAction(_ sender: UIButton) {
        print("Button tapped")
    }

  override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
   // Dispose of any resources that can be recreated.
  }
}

If you run the above code example, you should see a “Tap me” button. If you Tap on the button it should print the “Button tapped” message in the console.

Create UIButton Programmatically

 

Conclusion

In this tutorial, you learned how to create a UIButton programmatically in Swift, without using the storyboard or the interface builder. You learned how to:

  • Create a UIButton object and set its type, frame, background color, title, and tint color.
  • Add a click action to the UIButton using the addTarget method and a selector.
  • Add the UIButton to a view programmatically using the addSubview method.

For more Swift Code examples and tutorials, please check the Swift Code Examples page on this website.

If you are interested in video lessons on how to write Unit tests and UI tests to test your Swift mobile app, check out this page: Unit Testing Swift Mobile App

Happy Coding!

 

Leave a Reply

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