3

I have SettingsVC ("Photo" there are 2 switch) and MainVC ("Code" there is a function for adding haptic feedback buttons).

How can I make it so that when you turn off the Switch in Setting, then the function would stop working?

SettingsVC "Photo"

@IBAction func Vib(_ sender: UIButton) {
    let generator = UIImpactFeedbackGenerator(style: .light)
    generator.impactOccurred()
}
B2Fq
  • 876
  • 1
  • 8
  • 23

1 Answers1

5

You can store the switch state in UserDefaults and then check for it in your function.

In your switch action:

@IBAction func switchAction(sender: UISwitch) { 
    if sender.isOn {
        UserDefaults.standard.set(true, forKey: "SwitchState")
    } else {
        UserDefaults.standard.set(false, forKey: "SwitchState")
    }
}

In your MainVC func

@IBAction func Vib(_ sender: UIButton) {
    guard UserDefaults.standard.bool(forKey: “SwitchState”) else { return }

    let generator = UIImpactFeedbackGenerator(style: .light)
    generator.impactOccurred()
}
Francesco Deliro
  • 3,899
  • 2
  • 19
  • 24