且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在不加载视图的情况下接收通知

更新时间:2022-06-27 00:19:59

每次我关闭设置视图时,变量savedValue 都不会自行刷新.这是因为另一个 ViewController 没有每次都加载自己.我所做的是创建了一个新函数,该函数在调用通知时运行(即关闭设置视图时).代码如下:

The variable savedValue wasn't refreshing itself each time I dismissed the Settings View. This is because the other ViewController wasn't loading itself each time. What I did is I created a new function that runs when the notification is called (which is when Settings View is dismissed). Here is the code:

class ViewController: UIViewController {

@IBOutlet weak var testLabel: UILabel!    
var savedValue = UserDefaults.standard.bool(forKey: "sound")


override func viewDidLoad() {
        super.viewDidLoad()

    NotificationCenter.default.addObserver(self, selector: #selector(ViewController.retrieveValue), name: Notification.Name("nSound"), object: nil)

//For when the view appears the first time
    savedValue = UserDefaults.standard.bool(forKey: "sound")

    if (savedValue == true) {
        testLabel.text = "yes"
    } else {
        testLabel.text = "no"
    }

}

func retrieveValue() {

//refresh the savedValue variable       
            savedValue = UserDefaults.standard.bool(forKey: "sound")

//test the savedValue variable
            if (savedValue == true) {
                testLabel.text = "yes"
            } else {
                testLabel.text = "no"
            }

    }

请注意,addObserver 现在调用函数 retrieveValue().

Note that addObserver now calls the function retrieveValue().