Switch UI Element graphical issue

52 views Asked by At

I've implemented a switch ui element to my application. It acts as a music toggle and it works perfectly. however, once you leave the view controller and come back. the switches graphics are set to on but the actual value remains the same as what the user set previously

What could be causing this? and is there any way to fix that, I assume that would be confusing to the user to see the switch as on at all times whether its actually off or not.

@Robotic cat: I don't know what the prepareForsegue is...

the audioPlayer is set up globally in the main viewController.swift file

Relevent code:

import UIKit

class SettingsViewController: UIViewController {



    @IBAction func musicToggle(_ sender: UISwitch)
    {
        audioPlayer.prepareToPlay()
        if (sender.isOn == true)
        {
            playMusic()
        }
        else if (sender.isOn == false)
        {
            stopMusic()
        }
    }

    override func viewDidLoad() {
    super.viewDidLoad()


    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func playMusic()
    {
        audioPlayer.play()
        audioPlayer.numberOfLoops = -1
    }
    func stopMusic()
    {
        audioPlayer.stop()
    }

}
1

There are 1 answers

2
Chris Levely On

Ok, I've solved my issue thanks to Robotic Cat

What I needed to do was save the value of the switch to UserDefault and then grab that value in the viewDidAppear Function.

This also solved the problem that the music would play no matter what when the app was closed out and re-launched, however, I knew UserDefaults was the solution for that.