Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to recognise tap of Toggle Button for SwiftUI?

I have passed a constant value to Toggle since I want to perform certain acctions on value change of toggle and it needs to be done on Tap Gesture as internally I might need to change the value of toggle as well. But hus code is not working

    @State private var toggle = false
    var body: some View {
           VStack {
               Toggle(isOn: .constant(toggle)) {
                    Text("Hello World")
                }
                .padding()
                .onTapGesture {
                    print("Tapped")
                    self.toggle.toggle()
                }
            }

        }
}
like image 781
Abhishek Avatar asked Feb 02 '26 20:02

Abhishek


1 Answers

Toggle(isOn: Binding(
get:{isToggled},
set:{v in
  isToggled = v
  customAction()
})) {
  Text("Status")
}

Custom action code does not get triggered if the state is modified. But will be triggered on UI interaction

like image 153
sakthig Avatar answered Feb 04 '26 14:02

sakthig