0

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

        }
}
Abhishek
  • 93
  • 7
  • 1
    Try `onChange` of `toggle`. The UI part will be irrelevant because it will trigger when the variable changes. – lorem ipsum May 15 '22 at 11:35
  • Does this answer your question https://stackoverflow.com/a/63360119/12299030? Or this one https://stackoverflow.com/a/63287584/12299030? – Asperi May 15 '22 at 11:52
  • I cannot use the `onChange` method as it will be triggered whenever the toggle value gets changed. In my actual code I need to call an api when toggle value changes and also in one case I need to change the toggle value from application. If I use `onChange` method , everytime the value changes whether from application or from UI this method will trigger and it will go infinite loop ,so to avoid this I want to use Tap Gesture. – Abhishek May 15 '22 at 12:51
  • @Asperi , no in this case as well `onTapGesture` is not triggered – Abhishek May 15 '22 at 12:59
  • 1
    Then you need just proxy Binding (like in https://stackoverflow.com/a/59341588/12299030) to intercept change in `set` and either transfer it to state or skip, and w/o additional tap gesture. – Asperi May 15 '22 at 13:16
  • @Asperi , But how will it know whether the value is changed by application code or the value is changed by the UI? – Abhishek May 15 '22 at 13:29
  • You'll come in binding set *only* from UI, from API you update state or vm directly and Toggle read it via get. – Asperi May 15 '22 at 13:32
  • You might be better off creating your own toggle. Like a `Button` that looks like a toggle. it doesn't have to be a button it can be any `View` object and then you can have the on tap gesture. – lorem ipsum May 15 '22 at 17:07

1 Answers1

0
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

sakthig
  • 2,187
  • 3
  • 18
  • 22