Design Converter
Education
Last updated on Jan 21, 2025
Last updated on Jan 20, 2025
When building dynamic and interactive user interfaces in iOS development, you will frequently rely on components that help you elegantly switch between different data views or options. The UISegmentedControl is a perfect candidate for this purpose. A UISegmentedControl is a specialized segmented control that lets you display multiple segments—each of which can hold a title, image, or even custom content—allowing the user to quickly switch between distinct content categories.
This blog will help you understand how to initialize, customize, and work with a UISegmentedControl. You will learn about setting titles, icons, background image elements, and how to leverage text attributes.
Let’s dive deep into this essential UI element and discover how a UISegmentedControl can enhance your app’s look and feel.
Before you start customizing, you need to understand how to initialize your segmented control. A UISegmentedControl typically displays multiple segments in a linear set. Each of these segments can display a title (such as text labels) or an image, letting you define the exact look and feel you desire. You can initialize this control using a variety of init methods. For instance, using init(frame: CGRect) gives you manual control over the position and frame of the control, while other initializers let you directly supply an array of segments—either strings, images, or UIActions.
A common required init scenario is programmatically setting up a UISegmentedControl and adding it to your view controller. For a UISegmentedControl that is defined in a storyboard or Xib file, you might rely on required init?(coder: NSCoder) to set it up. Another required init approach involves using init(items: [Any]?), where the array might consist of strings or images. When you create segments from an array, you can easily display several options and let users switch between them. In some cases, you may even use init(frame: CGRect, actions: [UIAction]) to directly bind actions to each segment—this can be pretty straightforward in terms of connecting code and behavior.
Below is a simple example of how you might initialize a UISegmentedControl in override func viewDidLoad() inside your view controller:
1override func viewDidLoad() { 2 super.viewDidLoad() // This is the override func viewdidload point 3 let segmentItems = ["First", "Second", "Third"] 4 let mySegmentedControl = UISegmentedControl(items: segmentItems) 5 mySegmentedControl.frame = CGRect(x: 50, y: 100, width: 220, height: 30) // defining position and frame 6 mySegmentedControl.selectedSegmentIndex = 0 7 self.view.addSubview(mySegmentedControl) 8}
When it comes to customizing the appearance of a UISegmentedControl, there are numerous approaches. You can set a background image for the entire control or for individual segments. Using setBackgroundImage(_:for:barMetrics:) allows you to replace the default background with something more vibrant, maybe a subtle blue gradient or a sleek texture. Additionally, you can configure a divider image between segments to further refine the look. Adjusting text attributes at the normal state can help you define the font style, color, and other details to enhance contrast.
The UISegmentedControl also allows you to customize segment widths. By doing so, you can achieve consistent content widths or even apply a positioning offset to ensure perfect alignment. Use the appearance proxy or modify each property locally. Setting a background color for the selected segment can help visually highlight the currently selected segment and give the user a clear indication of which choice is active. Remember, you can avoid putting random styling if it doesn’t match your overall app design. Carefully select a background that complements your brand colors.
For example, to customize appearance attributes at runtime, you might do:
1let titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white] 2mySegmentedControl.setTitleTextAttributes(titleTextAttributes, for: .normal) // sets text attributes for normal state 3mySegmentedControl.setBackgroundImage(UIImage(named: "segBackground"), for: .normal, barMetrics: .default) // sets a background image 4mySegmentedControl.setDividerImage(UIImage(named: "dividerIcon"), forLeftSegmentState: .normal, rightSegmentState: .normal, barMetrics: .default)
A key feature of UISegmentedControl is that each segment can display a unique title or image. You can use setTitle(:forSegmentAt:) to change the title and setImage(:forSegmentAt:) to add an image to a specific segment. If you have icons that represent categories, placing them in your segments can be an elegant solution.
It’s also possible to create an action for a particular segment with setAction(_:forSegmentAt:). This lets you define behavior that triggers when a user selects that segment. For example, if the user chooses a certain category, you might print a message or save certain preferences. If you need to remove segments, use removeSegment(at:animated:) or removeAllSegments() to rebuild the control dynamically. This is helpful if your data model changes and you need to show fewer or more segments. You can also access the title or image currently assigned to a segment using titleForSegment(at:) or imageForSegment(at:).
As a user interacts with your segmented control, you will want to know which segment is selected. The index of the currently selected segment is accessible through the selectedSegmentIndex property. Monitoring changes is crucial: you can register a target-action pair that fires when valueChanged occurs, allowing you to switch the displayed content in your view controller.
You might also programmatically switch the selection by setting selectedSegmentIndex to a different index. Make sure to print debug statements or save user preferences whenever the selection changes. For a custom segmented control, consider implementing the delegate pattern or using a horizontal stack of UIButtons to replicate the behavior of a traditional UISegmentedControl.
1mySegmentedControl.addTarget(self, action: #selector(segmentValueChanged(_:)), for: .valueChanged) 2 3@objc func segmentValueChanged(_ sender: UISegmentedControl) { 4 let selectedIndex = sender.selectedSegmentIndex 5 print("Selected segment index: \(selectedIndex)") // using print to log changes 6 // switch your displayed content here 7}
If the default behavior of UISegmentedControl does not meet your requirements, you can build a custom segmented control by subclassing it or by using a horizontal UIStackView containing UIButton elements. This provides more control over the position, offset, width, and property changes that may not be directly available.
You can define a function to handle advanced layouts, create a variable to track the selected segment, or even implement animations when the user switches segments. Consider using the appearance proxy to apply universal changes or working at the layer level (layer) to create sophisticated visuals. Remember, with a more custom approach, you must handle init methods carefully, ensuring that required init calls are properly implemented.
When using UISegmentedControl in a view controller, remember these tips:
• Use it to display clear categories with appropriate title and image combinations.
• Always ensure the default selection is meaningful.
• Customize the appearance to align with your app’s design language.
• Make sure the index of the selected segment is always kept in sync with the displayed data.
• Save user preferences if the user commonly interacts with the segmented control to remember their last choice.
• Define a function to handle segment changes and print or log the selection.
• Use post notifications or a delegate if multiple parts of your code need to react to segment changes.
Sometimes you may face issues where changing the background color of a selected segment does not take effect due to default iOS styling. In such cases, you can access the subviews of the UISegmentedControl and reorder them by their frame or position. Another approach is to override func viewDidLoad() and apply appearance or styling code once the view is fully loaded. If you need to show a divider image that aligns perfectly, consider using a positioning offset or content positioning adjustments.
If you struggle to properly remove segments or update segment configurations, verify that your array of items is correct, and your init methods are correctly called. Also, print debugging information or use a post console log to confirm that the changes are applied at the right moment. By carefully examining the object state, ensuring all methods are properly invoked, and verifying all values are set to normal, you can resolve these issues effectively.
The UISegmentedControl empowers you to build intuitive, organized UIs in your iOS development journey. By understanding how to create and configure segments, set a custom background image, tweak content widths, apply text attributes, and handle a custom layout, you gain the flexibility to produce a polished, user-friendly interface. Whether you need to define unique segment styles, insert a divider image, manage offset positioning, or link your segmented control to changes in your app’s content, the UISegmentedControl is a pretty straightforward yet powerful tool.
As you continue, try using a storyboard or code-only approach to set it up, save your modifications in a version control project, experiment with blue highlights or contrast in your property settings, and print console logs to debug behavior. Use icons or string titles to improve recognizability, post your UI designs for feedback, and refine as needed. By doing so, you will not only gain proficiency in working with a UISegmentedControl, but also ensure a seamless experience for your user.
In short, the UISegmentedControl is a versatile UI element that, once mastered, helps you avoid putting unnecessary complexity into your UI. With careful consideration of frame, values, and appearance, you can switch smoothly between segments and deliver a clean, modern interface that resonates with your view controller and overall app design.
Tired of manually designing screens, coding on weekends, and technical debt? Let DhiWise handle it for you!
You can build an e-commerce store, healthcare app, portfolio, blogging website, social media or admin panel right away. Use our library of 40+ pre-built free templates to create your first application using DhiWise.