0
0
iOS Swiftmobile~5 mins

Button and action handling in iOS Swift

Choose your learning style9 modes available
Introduction

Buttons let users tap to do something in your app. Action handling means making the app respond when a button is tapped.

When you want the user to submit a form by tapping a button.
When you want to navigate to a new screen after a button tap.
When you want to start or stop a task with a button press.
When you want to show or hide information after tapping a button.
Syntax
iOS Swift
let button = UIButton(type: .system)
button.setTitle("Tap me", for: .normal)
button.addTarget(self, action: #selector(buttonTapped), for: .touchUpInside)

@objc func buttonTapped() {
    // code to run when button is tapped
}

Use addTarget(_:action:for:) to connect the button tap to your code.

The @objc keyword is needed for the action method to work with the button.

Examples
This creates a button that prints a message when tapped.
iOS Swift
let button = UIButton(type: .system)
button.setTitle("Click me", for: .normal)
button.addTarget(self, action: #selector(handleClick), for: .touchUpInside)

@objc func handleClick() {
    print("Button clicked")
}
This button shows an alert popup when tapped.
iOS Swift
let button = UIButton(type: .system)
button.setTitle("Press here", for: .normal)
button.addTarget(self, action: #selector(showAlert), for: .touchUpInside)

@objc func showAlert() {
    let alert = UIAlertController(title: "Hello", message: "Button pressed!", preferredStyle: .alert)
    alert.addAction(UIAlertAction(title: "OK", style: .default))
    present(alert, animated: true)
}
Sample App

This app shows a button in the middle of the screen. When you tap it, an alert pops up saying "You tapped the button!".

iOS Swift
import UIKit

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let button = UIButton(type: .system)
        button.setTitle("Tap me", for: .normal)
        button.frame = CGRect(x: 100, y: 200, width: 120, height: 50)
        button.addTarget(self, action: #selector(buttonTapped), for: .touchUpInside)
        view.addSubview(button)
    }
    
    @objc func buttonTapped() {
        let alert = UIAlertController(title: "Button Tapped", message: "You tapped the button!", preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "OK", style: .default))
        present(alert, animated: true)
    }
}
OutputSuccess
Important Notes

Always set the button frame or constraints so it appears on screen.

Use .touchUpInside event to detect taps inside the button area.

Remember to add the button to your view with addSubview.

Summary

Buttons let users interact by tapping.

Use addTarget to connect button taps to your code.

Action methods must be marked with @objc to work.