Custom Segmented Control — SwiftUI

Umut Boz
KoçSistem
Published in
2 min readMay 22, 2024

In this article, you will find a Segmented Control example with a custom design within the SwiftUI framework. This method customizes the Segmented Control specifically designed for your application.

Segmented Controls

Apple by definition, A segmented control is a linear set of two or more segments, each of which functions as a button. Within a segmented control, all segments are usually equal in width. Like buttons, segments can contain text or images. Segments can also have text labels beneath them (or beneath the control as a whole). A segmented control can offer a single choice or multiple choices. (1).

its called segmented on SwiftUI Library and UISegmentedControl on UIKit Framework.

Custom Segmented Controls

To design according to the theme of your app, follow the methods below.

We will design a segmented control with two elements, for this we will manage it with an enum type consisting of 0 and 1.

// 0 : Camera
// 1 : PhotoLbirary

The design output is below, accordingly developed below. ⬇️

import Foundation
import SwiftUI

struct CustomSegmentedControl: View {
@Binding var preselectedIndex: Int
var options: [String]
// this color is coming theme library
let color = ThemeManager.shared.currentTheme.currentPallet.secondary

var body: some View {
HStack(spacing: 0) {
ForEach(options.indices, id:\.self) { index in
ZStack {
Rectangle()
.fill(color.opacity(0.2))

Rectangle()
.fill(color)
.cornerRadius(20)
.padding(2)
.opacity(preselectedIndex == index ? 1 : 0.01)
.onTapGesture {
withAnimation(.interactiveSpring()) {
preselectedIndex = index
}
}
}
.overlay(
Text(options[index])
)
}
}
.frame(height: 50)
.cornerRadius(20)
}
}

Custom Segmented Control class takes two parameters. The first parameter is for the currently selected item, the second is as an item array string. This array can be defined as a constant.

The important point is that the first parameter is marked as @Binding.

This parameter is the value we keep as @state and send with sourcetype in the view.

There is a small animation in the CODE that works with gesture.

VStack{
CustomSegmentedControl(preselectedIndex: $selectedSegmentSourceType,
options: [Localization.value("photos.title"), Localization.value("camera.title")])
}

Additionally, the value we change on the control will be made with the sourcetype variable on the view.

We can read the election status through this variable.

In the next article, we will use this segmented control and picker together.❤️‍🔥

Resources

--

--