Search code examples
iosswift3nsuserdefaultsxcode8uisegmentedcontrol

How to save the state of UISegmentedControl in Swift3 with userDefaults


I have a UISegmentedControl called langSeg with two indexes labeled [English & German] , which controls the language of labels in my app using the code below:

@IBAction func indexChanged(sender: UISegmentedControl) {

    switch langSeg.selectedSegmentIndex
    {
    case 0:

        let language = "en"
        let path = Bundle.main.path(forResource: language, ofType: "lproj")
        let bundle = Bundle(path: path!)
        headerLbl.text = bundle?.localizedString(forKey: "HLbl", value: nil, table: nil)
        UserDefaults.standard.set(["en"], forKey: "AppleLanguages")

    case 1:

        let language = "de"
        let path = Bundle.main.path(forResource: language, ofType: "lproj")
        let bundle = Bundle(path: path!)
        descLbl.text = bundle?.localizedString(forKey: "DLbl", value: nil, table: nil)
        UserDefaults.standard.set(["de"], forKey: "AppleLanguages")

    default:
        break;
    }
}

to switch between English and German languages and save the user's selection; this code is working fine, but when I relaunch my App after changing the language to German for example, the labels titles are saved in German language but the segmentedControl state changed back to the English title [index 0]. Please, I need help to save the user's selection of the UISegmentedControl, any help is really appreciated. I tried this code:

langSeg.selectedSegmentIndex = sender.selectedSegmentIndex
UserDefaults.standard.integer(forKey: "SegmentIndex")

inside

@IBAction func indexChanged(sender: UISegmentedControl)

After the switch brackets, but unfortunately it didn't work...


Solution

  • class ViewController: UIViewController {
    
        @IBOutlet weak var segmentedControl: UISegmentedControl!
    
        @IBAction func segmentSelected(_ sender: UISegmentedControl) {
    
            UserDefaults.standard.set(sender.selectedSegmentIndex, forKey: "chosenLanguage")
        }
    
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            if let value = UserDefaults.standard.value(forKey: "chosenLanguage"){
                let selectedIndex = value as! Int
                segmentedControl.selectedSegmentIndex = selectedIndex
            }
    
        }
    }