Sometimes, to provide a better user experience, we need to customize components. In this post, we’ll see how to customize the Toggle, as shown in the image:

Take a look at the code:
struct ContentView: View {
@State var toggle = false
var body: some View {
VStack {
Toggle(isOn: $toggle) {
Text("Hai bevuto a digiuno?")
}.toggleStyle(CustomToggleStyle(systemImage: "fork.knife", activeColor: .green))
.padding()
}
}
}
So we call the Toggle in the usual way, but we add a custom style to it.
Now, let’s see how to define the style:
struct CustomToggleStyle: ToggleStyle {
var systemImage: String = "checkmark"
var activeColor: Color = .green
func makeBody(configuration: Configuration) -> some View {
HStack {
configuration.label.font(.largeTitle).foregroundStyle(.orange).bold()
Spacer()
RoundedRectangle(cornerRadius: 60)
.fill(configuration.isOn ? activeColor : Color(.orange))
.overlay {
Circle()
.fill(.white)
.padding(3)
.overlay {
Image(systemName: systemImage)
.foregroundColor(configuration.isOn ? activeColor : Color(.gray))
}
.offset(x: configuration.isOn ? 10 : -10)
}
.frame(width: 80, height: 42)
.onTapGesture {
withAnimation(.spring) {
configuration.isOn.toggle()
}
}
}
}
}
TheCustomToggleStyle must conform to the ToggleStyle protocol, which requires the implementation of the makeBody function.
The Configuration contains the current state of the Toggle. To modify the label’s properties, we update Configuration.label. For the UI part, we create a RoundedRectangle with a circle overlay that changes position based on the toggle’s state (isOn). We also apply an animation when the toggle is tapped.
That’s all—enjoy customizing your Toggle!
Leave a Reply