NEW: Start my new Ultimate Portfolio App course with a free Hacking with Swift+ trial! >>

SOLVED: Toggle control action

Forums > SwiftUI

Hello.

Is there a simple clean way to add an action to a toggle control in SwiftUI.

Sorry is this one has been answered before. I'm sure it must have but can't find anything.

   

Not sure what action you want to do with a Toggle

Taken from Apple Developer Documentation - Toggle

You create a toggle by providing an isOn binding and a label. Bind isOn to a Boolean property that determines whether the toggle is on or off. Set the label to a view that visually describes the purpose of switching between toggle states.

@State private var vibrateOnRing = false

var body: some View {
    Toggle(isOn: $vibrateOnRing) {
        Text("Vibrate on Ring")
    }
}

   

I'm looking at having an action like a button with code dependent on the state of the toggle.

   

You can use an onChange handler observing the same state variable you are using for the Toggle.

struct Toggler: View {
    @State private var vibrateOnRing = false

    var body: some View {
        Toggle(isOn: $vibrateOnRing) {
            Text("Vibrate on Ring")
        }
        .onChange(of: vibrateOnRing) { value in
            //perform your action here...
            print(value)
        }
    }
}

   

Hi. That works. Thank you.

   

Hi everyone,

Just would to add another reply cause using .onChange is available only on iOS 14 and up, here it is my way of dealing with same question :


struct ContentView: View {
    @State private var isToggle : Bool = false {
            didSet {
                print("value did change")
            }
    }

    var body: some View {
        Toggle(isOn: self.$isToggle){
                    Text("Toggle Label ")
         }
    }
}

   

Hacking with Swift is sponsored by Instabug

SPONSORED Catch bugs as soon as they happen and know exactly why a crash occurred. Instabug's SDK grabs all the logs they need to fix bugs, crashes and performance issues in minutes instead of days. Get screenshots, device details, network logs, repro steps, and tons of other critical insights needed to resolve issues and prioritize product backlogs straight from your dashboard. It only takes a minute to integrate!

Get started now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.