Building Custom Styles on SwiftUI Views

How to make build custom Toggle View, button etc in SwiftUI?

Prafulla Singh
Aug 25, 2020 · 2 min read

In this tutorial, We are going to understand how can we use Styles to make reusable custom views.

Generic SwiftUI views usually have two components Configuration and Style. Configuration is where data for the view resides and Style is where view get build.

View              Style
Toggle ToggleStyle
Button PrimitiveButtonStyle
ProgressView ProgressViewStyle
TextField TextFieldStyle

For this tutorial, We are going to implement customs ToggleStyle and PrimitiveButtonStyle.

Building custom toggle style, First we are going to look at ToggleStyle protocol.

public protocol ToggleStyle {/// A view that represents the appearance and interaction of a toggle.
associatedtype Body : View
func makeBody(configuration: Self.Configuration) -> Self.Body
/// The properties of a toggle instance.
typealias Configuration = ToggleStyleConfiguration

As we can see if we can implement makeBody we can implement out own custom ToggleStyle but what is this Configuration. Let’s checkout the definition.

public struct ToggleStyleConfiguration {
/// A type-erased label of a toggle.
public struct Label : View {
public typealias Body = Never
public let label: ToggleStyleConfiguration.Label
public var isOn: Bool { get nonmutating set }
public var $isOn: Binding<Bool> { get }
///Basic Toggle Implementation:Toggle(isOn: <state isOn>, label: {
<Body Label>

We can map the configuration in above implementation to our basic definition. In makeBody we can utilise this to implement custom style. like following:

Custom Toggle

This gives us toggle state like following:

Similarly, a custom PrimitiveButtonStyle:


Similarly, all the basic views can be updated for the app use case to reduce code duplication.

The Startup

Get smarter at building your thing. Join The Startup’s +800K followers.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store