SwiftUI Toggle Button Style




    SwiftUI Recipes

    In this code, the state variable toggleIsOn is private, meaning it can only be accessed by the code inside the @State directive. The code declares a variable called body that is of type some View. The @State directive tells Xcode that this variable will be used to hold the view for the content of the content view. The code then declares a function called Toggle that takes two arguments: a reference to the object containing the toggle, and a boolean indicating whether the toggle is currently on or off. The function sets the state of the toggle to be either on or off depending on the value of the boolean argument. Finally, the function calls a style function called toggleStyle which sets the style of the button element to be .button and styles the text to be tinted in green.

    import SwiftUI
    // iOS 15+
    struct ContentView: View {
      @State private var toggleIsOn = false
      var body: some View {
        Toggle("Toggle", isOn: $toggleIsOn)
    Codiga Logo
    Codiga Hub
    • Rulesets
    • Playground
    • Snippets
    • Cookbooks
    • Security
    • Privacy Policy
    • Code Privacy
    • Terms of Service
    soc-2 icon

    We are SOC-2 Compliance Certified

    G2 high performer medal

    Codiga – All rights reserved 2022.