UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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.

3      

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")
    }
}

3      

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

3      

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)
        }
    }
}

5      

Hi. That works. Thank you.

3      

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 ")
         }
    }
}

3      

Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

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

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

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.