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
etc

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>
}).toggleStyle(<style>)

#programming #ios #swift #swiftui #mobile-app-development

Building Custom Styles on SwiftUI Views
3.75 GEEK