UIPickerView
ActionSheet
iOS Development
Swift
Mobile App Tutorial

Add UIPickerView a Button in Action sheet - How?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Adding a UIPickerView and button directly into a classic action sheet is a legacy pattern that can be fragile. In modern iOS, the reliable approach is to present a custom controller or use an input accessory with a picker-backed text field.

Short troubleshooting answers often solve the immediate error but miss maintainability concerns such as reproducibility, observability, and rollback safety. A complete implementation should make assumptions explicit, validate edge cases, and produce diagnostics that are useful during incidents.

When adapting snippets, verify version compatibility, runtime environment, and operational limits before rollout. Small contextual differences, such as framework version, deployment topology, or data shape, can change behavior significantly.

Core Sections

1. Establish a minimal correct solution

A common UIKit solution is to use a hidden text field with inputView set to UIPickerView and inputAccessoryView set to a toolbar with Done/Cancel buttons.

swift
1final class PickerHostVC: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {
2    let picker = UIPickerView()
3    let field = UITextField(frame: .zero)
4
5    override func viewDidLoad() {
6        super.viewDidLoad()
7        picker.dataSource = self
8        picker.delegate = self
9        field.inputView = picker
10
11        let bar = UIToolbar()
12        bar.sizeToFit()
13        bar.items = [
14            UIBarButtonItem(systemItem: .cancel, primaryAction: UIAction { _ in self.field.resignFirstResponder() }),
15            UIBarButtonItem.flexibleSpace(),
16            UIBarButtonItem(systemItem: .done, primaryAction: UIAction { _ in self.field.resignFirstResponder() })
17        ]
18        field.inputAccessoryView = bar
19    }
20}

This baseline should stay intentionally simple so correctness is easy to verify. Once the minimal behavior is confirmed, extend it with error handling and performance considerations rather than starting with complex abstractions.

2. Harden for production requirements

If you need sheet-style UX, present a custom bottom sheet view controller containing picker and buttons. This is more controllable than hacking UIAlertController internals.

swift
1let vc = PickerBottomSheetController(items: items)
2if let sheet = vc.sheetPresentationController {
3    sheet.detents = [.medium()]
4}
5vc.onConfirm = { selected in
6    print("selected", selected)
7}
8present(vc, animated: true)

Production hardening usually includes explicit validation, clear failure semantics, and safe resource lifecycle management. It also helps to centralize configuration and shared logic so behavior remains consistent across environments and teams.

3. Validate and operate with confidence

Test keyboard, safe-area, and rotation behavior thoroughly. Picker interactions are highly stateful, and dismissal bugs often appear when presenting repeatedly or switching between modal styles.

Add a practical verification loop with one happy-path test, one edge-case test, and one failure-path test. Pair tests with lightweight runtime signals such as error rates, latency percentiles, or startup checks so regressions are detected early.

Operational readiness includes rollback planning. Even correct code may fail under unexpected dependencies or data. Documenting rollback steps and fallback behavior reduces recovery time and deployment risk.

Implementation depth also includes long-term operability. Define clear ownership of configuration, data contracts, and failure handling so support engineers can diagnose issues without reverse engineering intent from old commits. Where possible, capture representative input and output examples in tests, because executable examples age better than prose-only documentation.

For production systems, add lightweight observability close to the critical path: structured logs for key decisions, counters for failure categories, and latency metrics around expensive operations. These signals should map to user impact directly so on-call responders can prioritize correctly under pressure. Strong observability turns debugging from guesswork into a bounded investigation.

Finally, prepare rollback and fallback behavior before deploying significant changes. Even technically correct updates can fail due to environment differences, data anomalies, or dependency upgrades. A preplanned rollback path, feature flag, or degraded-mode strategy reduces mean time to recovery and allows teams to iterate quickly without risking prolonged outages.

Common Pitfalls

  • Embedding custom subviews in UIAlertController with unsupported assumptions.
  • Forgetting to retain picker data source values while sheet is visible.
  • Missing accessibility labels for picker rows and confirm buttons.
  • Not handling iPad presentation anchors for sheet-style modals.
  • Losing selected value on dismissal due to weak ownership patterns.

Summary

Use picker input views or custom sheet controllers instead of fragile action-sheet hacks. Modern UIKit APIs provide cleaner lifecycle and accessibility behavior. Pair implementation detail with testing and operational safeguards so the solution remains reliable as code, dependencies, and infrastructure evolve.


Course illustration
Course illustration

All Rights Reserved.