dbanon
dbanon

Reputation: 31

What is the best way to record UISwitch state in UserDefaults in Swift 3

I have a settings view in my (future) app, with 4 UISwitch. I want to use the UserDefaults class to record the switches state.

I created a struct "SettingsKey" with 4 properties (keys) to save each switch state :

struct SettingsKeys {
  static let appShowContactsPhoto = "app.showContactsPhoto"
  static let appShowAge = "app.showAge"
  static let widgetShowContactsPhoto = "widget.showContactsPhoto"
  static let widgetShowAge = "widget.showAge"
}

To load the data, I use 4 "UserDefaults.standard.bool(forKey: key)" for the 4 properties in SettingsKeys, in the "viewDidLoad" method.

What is the best way to save the data? I don't want to create 4 actions in my view controller (one "valueChanged" action for each switch), so I just created one. But how to map each UISwitch with the righ "SettingsKey" property? I want a generic code (one instruction?), I don't want my code to be like this :

if sender = switch1 then record data with this key
else if sender = switch2 then record data with this key
else if ...

Maybe with the UIView tags?

Thanks.

Upvotes: 3

Views: 247

Answers (2)

dbanon
dbanon

Reputation: 31

I used the UIView.tag property, as proposed by wolverine :

  • 1st UISwitch.tag = 0
  • 2nd UISwitch.tag = 1
  • ...

Then I modified my structure :

struct SettingsKeys {
  // Application Settings
  static let appShowContactsPhoto = "app.showContactsPhoto"
  static let appShowAge = "app.showAge"

  // Widget Settings
  static let widgetShowContactsPhoto = "widget.showContactsPhoto"
  static let widgetShowAge = "widget.showAge"

  // All settings
  static let serialized = [
    0: appShowContactsPhoto,
    1: appShowAge,
    10: widgetShowContactsPhoto,
    11: widgetShowAge,
  ]
}

My action :

// Click on a switch button
@IBAction func changeSetting(_ sender: UISwitch) {
  UserDefaults.standard.set(sender.isOn, SettingsKeys.serialized[sender.tag]!)
}

It works fine!

Upvotes: 0

Wolverine
Wolverine

Reputation: 4329

You can try something like this

@IBAction func changeSettings(_ sender: UISwitch) {

    switch sender.tag {
    case 1:
        // Change for switch1

        break
    case 2:
        // Change for switch2

        break
    case 3:
        // Change for switch3, etc
        break

    default:
        print("Unknown Switch")
        return
    }

}

You can set the Tags(Unique Number to identify your view/Switch).

(In Above example they are 1, 2 3) respectively for each switch.

Upvotes: 2

Related Questions