使 UISwitch hide/unhide 在切换时成为标签 on/off

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

MeditationSettingsViewController 有一个 UISwitch 通过 Segue 链接到 MeditationScreenViewControllerUISwitch 不会隐藏来自 MeditationScreenViewController 的名为 phaselabel 的标签中的文本,而是显示 MeditationSettingsViewController 屏幕。我如何获得它,以便开关不会执行此操作,而是在打开开关时隐藏和取消隐藏 phaselabel 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
    }
}

尝试使用NSNotificationCenter让两个视图控制器知道开关状态的变化。

MeditationSettingsViewController中的showCycleTitleChanged函数中,这样做:

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

MeditationScreenViewController中,像这样收听通知:

viewDidLoad中:

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

同时添加这个函数来处理通知:

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