Mastering UISegmentedControl in UIKit: A Developer's Guide
UISegmentedControl is a powerful UIKit component that allows users to choose from a small set of options. This article provides a comprehensive guide to integrating and customizing segmented controls in your iOS applications, from basic setup to advanced styling and interaction handling. Discover how to enhance user experience with this versatile UI element.

Introduction to UISegmentedControl
The UISegmentedControl is a standard UI element in UIKit that presents users with a horizontal list of mutually exclusive options. It's ideal for situations where you want the user to select one choice from a small, predefined set, such as viewing options (e.g., "List" vs. "Grid"), filtering content (e.g., "All" vs. "Favorites"), or switching modes within an application.
UISegmentedControl inherits from UIControl, which means it participates in the target-action mechanism, allowing you to easily respond to user selections. It's a highly customizable control, letting you define both the number of segments and their content, which can be either text or images.
When to use UISegmentedControl
- Switching Views/Modes: Quickly toggle between different display styles or operational modes within a screen.
- Filtering Content: Offer simple filters for data displayed in a list or collection.
- Defining Scope: Allow users to choose a specific scope for an action or data display.
Key Considerations
- Limited Options: Best for 2-5 options. More than that can become visually cluttered and difficult to tap accurately.
- Mutually Exclusive: Only one segment can be selected at a time, making it unsuitable for multiple-choice selections.
- Always Visible: All options are always visible, which is different from a dropdown menu. Ensure your segment titles are concise and clear.
Basic Setup and Initialization
You can initialize a UISegmentedControl either programmatically or by adding it to your storyboard or XIB file. Programmatic setup offers greater flexibility and is often preferred for dynamic interfaces. When creating it programmatically, you typically provide an array of titles or images for the segments.
Let's walk through creating a UISegmentedControl with textual segments and adding it to a view controller. You'll then configure its initial selected segment and set up its Auto Layout constraints.
In the example above, we create an instance of UISegmentedControl with three segments. We then set its selectedSegmentIndex to 0 to ensure a default selection. Crucially, translatesAutoresizingMaskIntoConstraints is set to false to use Auto Layout for positioning, and then we define constraints to center it horizontally and pin it to the top safe area with leading and trailing indents.
Compatibility Notes
UISegmentedControl has been available since iOS 2.0. Its core functionality remains consistent across modern iOS versions (iOS 13+).
Handling User Interaction
To make your UISegmentedControl interactive, you need to respond to the valueChanged event. This event fires whenever the user taps a different segment. You achieve this using the target-action mechanism, which is a fundamental pattern in UIKit for handling control events.
When the valueChanged event occurs, the associated target object's specified action method is called. This method typically takes the sender of the event (the UISegmentedControl itself) as an argument, allowing you to query its selectedSegmentIndex property to determine which segment is currently active.
Remember to declare your action method with the @objc attribute if your class is not inheriting from NSObject or if you're using it in an Objective-C runtime context. This ensures the method is visible to the Objective-C runtime mechanisms that power target-action.
Programmatic Selection
You can also programmatically control which segment is selected using the selectedSegmentIndex property:
Setting selectedSegmentIndex programmatically does not trigger the valueChanged event. If you need to trigger the same logic as a user tap, you must call your action method explicitly after setting the index, or encapsulate the common logic in a separate helper method.
Customizing Appearance (Styling)
While UISegmentedControl has a clean, default appearance, UIKit provides ample opportunities for customization to match your app's branding. You can adjust colors, fonts, background images, and even the divider images between segments.
Tint Color (iOS 13+)
For modern iOS versions, the selectedSegmentTintColor property is the primary way to customize the background color of the selected segment. The overall tint of the unselected segments and borders will often derive from the control's tintColor.
Segment Content
You can set titles or images for each segment. Mixing titles and images within the same control is generally discouraged for visual consistency.
Text Attributes (iOS 5.0+)
You can customize the text appearance for different control states (normal, highlighted, selected, disabled).
Background and Divider Images (iOS 5.0+)
For more advanced visual customization, you can set background images for segments in different states and provide custom divider images.
These background and divider image properties offer granular control, but often selectedSegmentTintColor and setTitleTextAttributes provide sufficient styling for most modern iOS apps.
UISegmentedControl in Storyboards/XIBs
Integrating UISegmentedControl using Interface Builder (Storyboards or XIBs) is straightforward. You drag the component from the Object Library onto your canvas and then configure its properties in the Attributes Inspector.
- Drag and Drop: Find "Segmented Control" in the Object Library and drag it onto your view controller's view.
- Number of Segments: In the Attributes Inspector, you can adjust the
Segmentscount. Each segment gets its own input field forTitleand can optionally have anImage. - Default Selection: Set the
Selectedsegment index. Remember that segmented controls should always have a default selection. - Auto Layout: Use Auto Layout to position and size your segmented control appropriately within its superview.
- Connections: To handle
valueChangedevents, drag from the segmented control to your view controller in the Assistant Editor while holding Control. SelectActionas the Connection type, provide a name for your method (e.g.,segmentChanged), and chooseValue Changedas the Event.
This automatically generates an @IBAction method in your view controller, allowing you to write Swift code to respond to user interactions just as with programmatic setup.
Best Practices and Advanced Tips
To ensure your UISegmentedControl provides an excellent user experience, consider these best practices and advanced tips:
-
Provide a Default Selection: Users should always see one segment selected when a segmented control appears. This signals that it's an active control and prevents ambiguity.
-
Fewer is Better: Aim for 2-5 segments. More options can make segments too small, difficult to tap, and the text hard to read. If you need more options, consider a different UI element like a
UIPickerViewor a table view with selection. -
Clear and Concise Titles/Images: Use short, descriptive text or easily recognizable icons. Avoid jargon.
-
Consistent Content Type: Stick to either all text segments or all image segments. Mixing them can look inconsistent.
-
Accessibility:
UISegmentedControlis inherently accessible. VoiceOver users will hear the selected segment and can easily swipe to navigate and activate other segments. Ensure your segment titles are descriptive. -
Dynamic Segment Management: If your segments need to change based on application state or user data, you can programmatically add or remove segments using
insertSegment(withTitle:at:animated:),insertSegment(withImage:at:animated:), andremoveSegment(at:animated:).swift
By following these guidelines, you can create effective and user-friendly UISegmentedControl instances in your UIKit applications.
Common Interview Questions
What's the difference between `UISegmentedControl` and a `UIPickerView`?
`UISegmentedControl` is designed for selecting one option from a small, fixed, and always visible set of choices (typically 2-5). `UIPickerView` is used for selecting one or more items from a larger, often dynamic, list of choices in a scrollable wheel format. Picker views typically appear modally or at the bottom of the screen to save space, while segmented controls are inline UI elements.
How do I change the color of the selected segment in `UISegmentedControl` on iOS 13 and later?
On iOS 13 and later, you should use the `selectedSegmentTintColor` property to change the background color of the selected segment. For example: `segmentedControl.selectedSegmentTintColor = .systemRed`. For earlier versions, or more complex customizations, you might need to use `setBackgroundImage(_:for:barMetrics:)`.
Can I use both text and images in the same `UISegmentedControl`?
While it's technically possible, it's generally discouraged for visual consistency and a cleaner user interface. It's best practice to use either all text titles or all images for the segments within a single `UISegmentedControl`.
How do I get the selected segment's title or index?
You can get the index using `segmentedControl.selectedSegmentIndex`. Once you have the index, you can retrieve the title (if it's a text segment) using `segmentedControl.titleForSegment(at: selectedIndex)` or the image using `segmentedControl.imageForSegment(at: selectedIndex)`.
Why isn't my `valueChanged` action firing when I set `selectedSegmentIndex` programmatically?
Setting the `selectedSegmentIndex` property programmatically does not automatically trigger the `valueChanged` event. This is by design, as it's an internal change, not a user interaction. If you need to execute the same logic as your action method, you must explicitly call that method or a shared helper method after programmatically setting the index.