A Deep Dive into Swift’s UIKit UISegmentedControl

Marcus Ziadé
3 min readJul 26, 2023

--

UISegmentedControl is an essential UI component within the UIKit framework for iOS development. As a convenient interface for users to make selections, UISegmentedControl includes numerous properties and functionalities that allow customization. Here, we will delve into each of these properties and how to effectively use them in your iOS applications.

Creation and Initialization of UISegmentedControl

init(items: [Any]?)

This initializer lets you create a UISegmentedControl with an array of strings or images. The variety will be used to set the title or image for each segment in the control.

let segmentedControl = UISegmentedControl(items: ["Option 1", "Option 2", UIImage(named: "Icon")])

init(frame: CGRect, actions: [UIAction])

In iOS 15, Apple introduced a new initializer to create a segmented control with an array of UIAction instances, providing a way to specify an action directly when creating the segmented control:

let action1 = UIAction(title: "Option 1", handler: { _ in print("Option 1 selected") })
let action2 = UIAction(title: "Option 2", handler: { _ in print("Option 2 selected") })
let segmentedControl = UISegmentedControl(frame: .zero, actions: [action1, action2])

init(frame: CGRect) and init?(coder: NSCoder)

The first of these initializers is used when you want to define the control’s size and position manually. The latter is used when the power is loaded from a Storyboard or Xib file.

Managing Segment Content

The setTitle(_:forSegmentAt:) and setImage(_:forSegmentAt:) methods let you set the title and image for each segment, respectively. Their counterparts, titleForSegment(at:) and imageForSegment(at:), fetch the current title and image:

segmentedControl.setTitle("New Option 1", forSegmentAt: 0)
let title = segmentedControl.titleForSegment(at: 0)
segmentedControl.setImage(UIImage(named: "New Icon"), forSegmentAt: 2)
let image = segmentedControl.imageForSegment(at: 2)

Managing Segment Actions

setAction(_:forSegmentAt:) allows you to place an action for a specific part while actionForSegment(at:) Fetches the action for a segment:

let newAction = UIAction(title: "New Option 1", handler: { _ in print("New Option 1 selected") })
segmentedControl.setAction(newAction, forSegmentAt: 0)

Managing Segments

With numberOfSegments, you can retrieve the total number of features. insertSegment(action:at:animated:), insertSegment(with:at:animated:) and insertSegment(withTitle:at:animated:) allow you to add segments to the control while removeSegment(at:animated:) and removeAllSegments() allow you to remove segments:

let totalSegments = segmentedControl.numberOfSegments
segmentedControl.insertSegment(withTitle: "Option 3", at: 2, animated: true)
segmentedControl.removeSegment(at: 0, animated: true)

selectedSegmentIndex Retrieves or sets the index of the currently selected segment. To deselect all segments, you can set this property to UISegmentedControl.noSegment.

Managing Segment Behavior and Appearance

The isMomentary property controls whether the segmented control reverts to its non-selected state after the user releases the touch.

The setEnabled(_:forSegmentAt:) and isEnabledForSegment(at:) methods control and check the enabled state of a segment:

segmentedControl.setEnabled(false, forSegmentAt: 0)
let isEnabled = segmentedControl.isEnabledForSegment(at: 0)

setContentOffset(_:forSegmentAt:) and contentOffsetForSegment(at:) Adjust and return the offset for a segment's content:

segmentedControl.setContentOffset(CGSize(width: 10, height: 0), forSegmentAt: 0)
let offset = segmentedControl.contentOffsetForSegment(at: 0)

setWidth(_:forSegmentAt:) and widthForSegment(at:) Set and get the width of a segment:

segmentedControl.setWidth(100, forSegmentAt: 0)
let width = segmentedControl.widthForSegment(at: 0)

apportionsSegmentWidthsByContent Dictates whether the control adjusts segment widths based on their content widths.

Customizing Appearance

selectedSegmentTintColor sets the color for the selected segment. setBackgroundImage(_:for:barMetrics:) and backgroundImage(for:barMetrics:) set and retrieve the background image for a segment, respectively.

setDividerImage(_:forLeftSegmentState:rightSegmentState:barMetrics:) and dividerImage(forLeftSegmentState:rightSegmentState:barMetrics:) control the divider image between segments:

segmentedControl.setDividerImage(UIImage(named: "Divider"), forLeftSegmentState: .normal, rightSegmentState: .normal, barMetrics: .default)

setContentPositionAdjustment(_:forSegmentType:barMetrics:) and contentPositionAdjustment(forSegmentType:barMetrics:) Control and return the positioning offset for a segment's content:

segmentedControl.setContentPositionAdjustment(UIOffset(horizontal: 5, vertical: 0), forSegmentType: .left, barMetrics: .default)

setTitleTextAttributes(_:for:) and titleTextAttributes(for:) Set and retrieve the text attributes for a segment's title:

segmentedControl.setTitleTextAttributes([.foregroundColor: UIColor.red], for: .selected)
let attributes = segmentedControl.titleTextAttributes(for: .selected)

Final word

That’s it! You now know every detail about UISegmentedControl, one of UIKit’s most versatile and customizable components. This comprehensive understanding will empower you to enhance your app’s UI/UX design with more adaptable, user-friendly interfaces. Happy coding!

--

--