|

How to Trigger Action with Toggle in iOS SwiftUI

Toggles are a staple in mobile app development, allowing users to switch between two states. While creating a toggle in SwiftUI is straightforward, you might wonder how to execute actions when the toggle state changes. In this blog post, we’ll dive deep into how to perform actions with toggles in SwiftUI.

The Basic Toggle

First, let’s start with a simple example of creating a toggle:

import SwiftUI

struct ContentView: View {
    @State private var isOn = true

    var body: some View {
        Toggle("Enable Feature", isOn: $isOn).padding()
    }
    }

This will create a toggle that you can turn on and off, but it doesn’t do anything else.

Use onChange Modifier

The onChange modifier allows you to perform an action when the state changes. Here’s how to use it:

import SwiftUI

struct ContentView: View {
    @State private var isOn = true

    var body: some View {
        Toggle("Enable Feature", isOn: $isOn)
            .onChange(of: isOn) { newValue in
                print("Toggle is now \(newValue ? "ON" : "OFF")")
            }.padding()
    }
    }

With this code, the console will print the new state of the toggle each time it changes.

Use Ternary Operators

You can use ternary operators to execute different actions based on the toggle state:

.onChange(of: isOn) { newValue in
    newValue ? performOnAction() : performOffAction()
}

Here, performOnAction() and performOffAction() are functions that get called based on the toggle’s state.

Performing actions with toggles in SwiftUI is incredibly flexible. You can use the onChange modifier for basic actions or go more advanced with custom toggle styles. Whether you’re enabling features or controlling other views, actions in toggles offer a dynamic user experience.

Similar Posts

Leave a Reply