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:
- Using Storyboard (Interface Builder)
- Programmatically in Swift
2. Adding UIButton via Storyboard
- Open Main.storyboard in Xcode.
- Drag and drop a
UIButton
from the Object Library onto the view. - Customize its appearance using the Attributes Inspector (title, color, background).
- Create an IBAction in the ViewController:
@IBAction func buttonTapped(_ sender: UIButton) { print("Button was tapped!") }
- 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
Feature | Code Example |
---|---|
Set Title | myButton.setTitle("Click Me", for: .normal) |
Set Title Color | myButton.setTitleColor(.blue, for: .normal) |
Set Background Color | myButton.backgroundColor = .red |
Set Corner Radius | myButton.layer.cornerRadius = 10 |
Set Border | myButton.layer.borderWidth = 2 |
Set Image | myButton.setImage(UIImage(named: "icon.png"), for: .normal) |
Handle Tap | myButton.addTarget(self, action: #selector(buttonTapped), for: .touchUpInside) |
Disable Button | myButton.isEnabled = false |
Animate Button | UIView.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? 🚀