Search code examples
iosswift3segueviewcontrolleruiswitch

Make a UISwitch hide/unhide a label when it toggles on/off


MeditationSettingsViewController has a UISwitch which is linked to MeditationScreenViewController though a Segue. The UISwitch doesn't hide the text in the label called phaselabel from MeditationScreenViewController but instead displays the MeditationSettingsViewController screen. How do I get it so that the switch doesn't do this but hides and unhides phaselabel when the switch is turned on/off?

class MeditationSettingsViewController: UIViewController {

@IBAction func showCycleTitleChanged(_ sender: UISwitch) {
    if (sender.isOn == true)
    {
        func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
            if segue.identifier == "segue" {
                if let sendToDetailViewController = segue.destination as? MeditationScreenViewController {
                    sendToDetailViewController.isSwitchOn = sender!.isOn
                }

            }

class MeditationScreenViewController: UIViewController {

override func viewWillAppear(_ animated: Bool) {
    if isSwitchOn == true {
      //unhide the label
      self.phaseLabel.isHidden = true
        //set your label value here
    }
    else {
        self.phaseLabel.isHidden = false
    }
}

Solution

  • Try using NSNotificationCenter to let the two view controllers be aware of the switch state change.

    In MeditationSettingsViewController in the showCycleTitleChanged function, do this:

    @IBAction func showCycleTitleChanged(_ sender: UISwitch) {
        let data:[String: Bool] = ["state": sender!.isOn]
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: "switchChanged"), object: nil, userInfo: data)
    }
    

    In MeditationScreenViewController, listen to the notification like so:

    In viewDidLoad:

     NotificationCenter.default.addObserver(self, selector: #selector(self.showHideLabel(_:)), name: NSNotification.Name(rawValue: "switchChanged"), object: nil)
    

    Also add this function to handle the notification:

    func showHideLabel(_ notification: NSNotification) {
        self.phaselabel.isHidden = notification.userInfo?["state"] as? Bool
    }