iOS
UISegmentedControl
Swift
Programming
App Development

UISegmentedControl change number of segments programmatically

Interview Questions practice on Codemia

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

Browse interview questions

Introduction

UISegmentedControl is often initialized with a fixed set of segments, but it can also be updated at runtime when available options change. The important part is managing insertion, removal, and selected index safely so the control remains consistent with your view model. A good implementation updates segments from one source of truth instead of mutating the control ad hoc from multiple places.

Basic Segment Manipulation APIs

You can insert, remove, and replace segments programmatically.

swift
1import UIKit
2
3let control = UISegmentedControl(items: ["One", "Two"])
4control.insertSegment(withTitle: "Zero", at: 0, animated: false)
5control.removeSegment(at: 1, animated: false)
6control.setTitle("Final", forSegmentAt: 1)

Useful methods include:

  • 'insertSegment'
  • 'removeSegment'
  • 'removeAllSegments'
  • 'setTitle'
  • 'setImage'

These are enough for both incremental and full rebuild approaches.

Rebuild From a Data Model

For dynamic screens, rebuilding from an array is usually clearer than applying many scattered mutations.

swift
1import UIKit
2
3func applySegments(_ titles: [String], to control: UISegmentedControl) {
4    let previousSelection = control.selectedSegmentIndex
5    control.removeAllSegments()
6
7    for (index, title) in titles.enumerated() {
8        control.insertSegment(withTitle: title, at: index, animated: false)
9    }
10
11    if titles.indices.contains(previousSelection) {
12        control.selectedSegmentIndex = previousSelection
13    } else {
14        control.selectedSegmentIndex = titles.isEmpty ? UISegmentedControl.noSegment : 0
15    }
16}

This makes segment count changes deterministic and easy to test.

Handling Selection Correctly

Changing segment count can invalidate the selected index. If you remove the selected segment and do nothing else, the control may end up with no valid selection or an unexpected one.

Safe strategy:

  • preserve selection only if index still exists
  • otherwise choose a fallback segment or no selection

Always let the data model decide the fallback rather than guessing inside UI event handlers.

Updating in Response to User Choice

Example: a control that changes available filters based on mode.

swift
1final class ViewController: UIViewController {
2    private let control = UISegmentedControl()
3
4    override func viewDidLoad() {
5        super.viewDidLoad()
6        applySegments(["All", "Unread"], to: control)
7        control.addTarget(self, action: #selector(modeChanged), for: .valueChanged)
8    }
9
10    @objc private func modeChanged() {
11        if control.selectedSegmentIndex == 0 {
12            applySegments(["All", "Unread", "Flagged"], to: control)
13        } else {
14            applySegments(["Unread"], to: control)
15        }
16    }
17}

This kind of update is fine as long as segment state is not split across multiple controllers.

Animation and UX Considerations

Structural changes can be animated, but constant animated rebuilding may feel unstable. Prefer:

  • no animation for frequent updates
  • animation only when the user can understand why options changed
  • stable ordering of segments across updates

Unexpected movement in controls can hurt usability more than it helps.

UIKit Layout and Styling

After changing segments, you may also need to update:

  • selected index
  • enabled state per segment
  • content offset in surrounding scroll view if embedded in headers

Text length also matters. If segment titles vary widely, the control can become cramped. In those cases a custom segmented UI or a collection-based selector may fit better.

Accessibility

Dynamic segment changes should stay accessible. After rebuilding:

  • ensure titles are descriptive
  • preserve logical ordering
  • avoid unnecessary repeated announcements

If content changes significantly, consider whether VoiceOver users need additional context elsewhere on screen.

Debugging Checklist

If segment updates behave strangely:

  1. verify a single method owns segment rebuilding
  2. log selected index before and after update
  3. confirm target-action is not firing recursively
  4. make sure updates occur on main thread

Most bugs come from state drift rather than from UISegmentedControl itself.

Common Pitfalls

  • Mutating segments from multiple places without a shared source of truth.
  • Forgetting to fix selectedSegmentIndex after segment removal.
  • Rebuilding segments too frequently and creating unstable UI behavior.
  • Using titles so long that dynamic updates break layout clarity.
  • Performing UI updates off the main thread.

Summary

  • 'UISegmentedControl supports runtime segment count changes through insert and remove APIs.'
  • Rebuilding from a data array is usually cleaner than incremental random mutations.
  • Selection state must be revalidated whenever segment count changes.
  • Keep updates tied to one model-driven method for predictable behavior.
  • Favor clarity and stability over unnecessary animation when options change.

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.