Swift
iOS Development
Alert View
UIButton
User Interaction

Swift alert view with OK and Cancel which button tapped?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

In modern iOS code, the normal way to show an alert with OK and Cancel is UIAlertController plus two UIAlertAction handlers. You do not inspect some separate “which button was tapped” property later. Instead, you attach the code for each button directly to the action that represents it. That makes the user's choice explicit and easy to handle.

Use UIAlertController with Separate Action Handlers

A standard alert setup looks like this:

swift
1import UIKit
2
3final class ViewController: UIViewController {
4    func showDeleteAlert() {
5        let alert = UIAlertController(
6            title: "Delete File",
7            message: "Are you sure you want to delete this file?",
8            preferredStyle: .alert
9        )
10
11        let okAction = UIAlertAction(title: "OK", style: .default) { _ in
12            print("OK tapped")
13        }
14
15        let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { _ in
16            print("Cancel tapped")
17        }
18
19        alert.addAction(cancelAction)
20        alert.addAction(okAction)
21        present(alert, animated: true)
22    }
23}

When the user taps OK, the okAction closure runs. When the user taps Cancel, the cancelAction closure runs. That is the canonical answer.

The Closure Is the Button Callback

Each UIAlertAction receives a handler closure. That closure is where you react to the button tap.

This means you do not usually write code like:

  • show alert
  • wait
  • ask later which button won

Instead, the alert is event-driven. Each action carries its own response logic.

This model fits UIKit's general style and avoids global state just to remember which alert button was chosen.

If You Need Shared Logic, Use a Helper Method

Sometimes both buttons need to call into shared application logic. In that case, you can route the alert actions to helper methods or enums instead of putting all logic inline.

swift
1import UIKit
2
3enum AlertChoice {
4    case ok
5    case cancel
6}
7
8final class ViewController: UIViewController {
9    func showConfirmAlert() {
10        let alert = UIAlertController(
11            title: "Continue",
12            message: "Do you want to continue?",
13            preferredStyle: .alert
14        )
15
16        alert.addAction(UIAlertAction(title: "OK", style: .default) { _ in
17            self.handleAlertChoice(.ok)
18        })
19
20        alert.addAction(UIAlertAction(title: "Cancel", style: .cancel) { _ in
21            self.handleAlertChoice(.cancel)
22        })
23
24        present(alert, animated: true)
25    }
26
27    private func handleAlertChoice(_ choice: AlertChoice) {
28        switch choice {
29        case .ok:
30            print("User confirmed")
31        case .cancel:
32            print("User cancelled")
33        }
34    }
35}

This pattern is useful when the alert result feeds into a larger control flow.

Alert Style and Button Semantics Matter

UIKit also distinguishes button styles:

  • '.default for ordinary confirmation'
  • '.cancel for cancellation'
  • '.destructive for dangerous actions'

The style affects both appearance and user expectations. So even though “which button was tapped” is the direct question, you should also choose styles that match the meaning of the action.

For example, deleting a record often deserves a destructive action rather than a plain default action.

Present the Alert from the Correct View Controller

The alert must be presented from a view controller that is currently in the view hierarchy. If you call present too early or from an inactive controller, the alert may fail to appear or produce a runtime warning.

That means the correctness of the button handler is only part of the problem. The alert must also be presented from the right place in the UIKit life cycle.

Older UIAlertView Code Is Obsolete

Older Swift and Objective-C examples on the internet may use UIAlertView with delegate callbacks. That API is deprecated. If you see examples that talk about alert view tags or delegate methods to determine which button was tapped, treat them as legacy code, not modern UIKit guidance.

The modern answer is UIAlertController plus action handlers.

Common Pitfalls

The most common mistake is looking for a separate “selected button” return value after presenting the alert. UIAlertController does not work that way.

Another mistake is doing too much work inline in the action closures. If the result handling becomes large, move it into helper methods.

Developers also copy obsolete UIAlertView examples and then get confused when modern Swift code does not follow the same delegate pattern.

Summary

  • In modern Swift, detect OK versus Cancel by attaching separate handlers to UIAlertAction objects.
  • Each button runs its own closure when tapped.
  • Use helper methods or enums if the alert result feeds into larger logic.
  • Present the alert from a valid visible view controller.
  • Prefer UIAlertController; UIAlertView patterns are legacy and should not be used in new code.

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.