1. Home
  2. Docs
  3. iOS
  4. UI Controls
  5. Buttons (UIButton)

Buttons (UIButton)

What is UIButton?

UIButton is a UI control in UIKit that allows users to interact with an app by tapping a button. Buttons can display text, images, and background colors and trigger actions when tapped.


1. Creating a UIButton

There are two ways to add a UIButton in iOS development:

  1. Using Storyboard (Interface Builder)
  2. Programmatically in Swift

2. Adding UIButton via Storyboard

  1. Open Main.storyboard in Xcode.
  2. Drag and drop a UIButton from the Object Library onto the view.
  3. Customize its appearance using the Attributes Inspector (title, color, background).
  4. Create an IBAction in the ViewController: @IBAction func buttonTapped(_ sender: UIButton) { print("Button was tapped!") }
  5. Run the app and tap the button to see the console output.

3. Creating UIButton Programmatically

import UIKit

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

        // Create UIButton
        let myButton = UIButton(type: .system) // .system, .custom, .roundedRect
        myButton.setTitle("Tap Me", for: .normal)
        myButton.setTitleColor(UIColor.white, for: .normal)
        myButton.backgroundColor = UIColor.blue
        myButton.layer.cornerRadius = 10

        // Enable Auto Layout
        myButton.translatesAutoresizingMaskIntoConstraints = false

        // Add Action
        myButton.addTarget(self, action: #selector(buttonTapped), for: .touchUpInside)

        // Add to View
        view.addSubview(myButton)

        // Set Constraints
        NSLayoutConstraint.activate([
            myButton.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            myButton.centerYAnchor.constraint(equalTo: view.centerYAnchor),
            myButton.widthAnchor.constraint(equalToConstant: 150),
            myButton.heightAnchor.constraint(equalToConstant: 50)
        ])
    }

    @objc func buttonTapped() {
        print("Button was tapped!")
    }
}

Explanation:

  • Creates a button with “Tap Me” text.
  • Sets background color, text color, and corner radius.
  • Uses Auto Layout to center it on the screen.
  • Calls buttonTapped() when pressed.

4. UIButton Customization

4.1 Changing Title & Title Color

myButton.setTitle("Click Here", for: .normal)
myButton.setTitleColor(.red, for: .normal)

4.2 Setting Background Color

myButton.backgroundColor = UIColor.green

4.3 Adding Corner Radius (Rounded Button)

myButton.layer.cornerRadius = 10

4.4 Setting Button Border

myButton.layer.borderWidth = 2
myButton.layer.borderColor = UIColor.black.cgColor

4.5 Changing Font & Size

myButton.titleLabel?.font = UIFont.systemFont(ofSize: 18, weight: .bold)

5. UIButton States

A button has different interaction states, and you can customize each one:

myButton.setTitle("Pressed", for: .highlighted)
myButton.setTitleColor(.gray, for: .highlighted)

myButton.setTitle("Disabled", for: .disabled)
myButton.setTitleColor(.lightGray, for: .disabled)

Common States:

  • .normal – Default state.
  • .highlighted – When pressed.
  • .disabled – When inactive.

To disable a button:

myButton.isEnabled = false

6. UIButton with Images

6.1 Setting an Image

myButton.setImage(UIImage(named: "icon.png"), for: .normal)

6.2 Setting Background Image

myButton.setBackgroundImage(UIImage(named: "bg_image.png"), for: .normal)

6.3 Changing Image Position (Title + Icon)

myButton.setImage(UIImage(systemName: "star.fill"), for: .normal)
myButton.imageView?.contentMode = .scaleAspectFit
myButton.tintColor = .white
myButton.semanticContentAttribute = .forceRightToLeft // Moves image to the right of the text

7. UIButton Actions (Tap Events)

7.1 Handling Button Tap (Method 1 – addTarget)

myButton.addTarget(self, action: #selector(buttonTapped), for: .touchUpInside)

@objc func buttonTapped() {
    print("Button Pressed!")
}

7.2 Handling Button Tap (Method 2 – IBAction in Storyboard)

@IBAction func buttonTapped(_ sender: UIButton) {
    print("Button Pressed!")
}

Common Event Types:

  • .touchUpInside – Tap released inside button (most common).
  • .touchDown – Tap started.
  • .touchUpOutside – Tap released outside the button.

8. UIButton with Animation

UIView.animate(withDuration: 0.5) {
    myButton.transform = CGAffineTransform(scaleX: 1.2, y: 1.2) // Scale up
}

For a click effect:

UIView.animate(withDuration: 0.1, animations: {
    myButton.transform = CGAffineTransform(scaleX: 0.9, y: 0.9)
}) { _ in
    UIView.animate(withDuration: 0.1) {
        myButton.transform = CGAffineTransform.identity
    }
}

9. UIButton Inside a StackView

If you have multiple buttons and want to arrange them neatly, use UIStackView:

let stackView = UIStackView(arrangedSubviews: [button1, button2, button3])
stackView.axis = .vertical
stackView.spacing = 10
stackView.alignment = .center

view.addSubview(stackView)
stackView.translatesAutoresizingMaskIntoConstraints = false

NSLayoutConstraint.activate([
    stackView.centerXAnchor.constraint(equalTo: view.centerXAnchor),
    stackView.centerYAnchor.constraint(equalTo: view.centerYAnchor)
])

10. Summary

FeatureCode Example
Set TitlemyButton.setTitle("Click Me", for: .normal)
Set Title ColormyButton.setTitleColor(.blue, for: .normal)
Set Background ColormyButton.backgroundColor = .red
Set Corner RadiusmyButton.layer.cornerRadius = 10
Set BordermyButton.layer.borderWidth = 2
Set ImagemyButton.setImage(UIImage(named: "icon.png"), for: .normal)
Handle TapmyButton.addTarget(self, action: #selector(buttonTapped), for: .touchUpInside)
Disable ButtonmyButton.isEnabled = false
Animate ButtonUIView.animate(withDuration: 0.3) { myButton.alpha = 0.5 }

Conclusion

  • UIButton is a crucial UI component for user interaction.
  • Supports text, images, background colors, and animations.
  • Can be created via Storyboard or programmatically.
  • Use Auto Layout for responsive designs.

Would you like a complete example project with multiple button styles? 🚀