swiftviewcontrolleruislidernotificationcenter

How to send and receive UISlider value from one view controller to another


I'm trying to use NotificationCenter to send slider values (audio volume) to another view controller which contains the all the audio engine that I need. From the sender VC I tried this:

@IBAction func vol1ChangedFromMixer(sender: UISlider) {
    NotificationCenter.default.post(name: Notification.Name(rawValue: "vol1FromMixer"), object: nil)
    }

And then at receiver VC, in viewDidLoad:

//vol from mixer
    NotificationCenter.default.addObserver(self, selector: #selector(vol1FromMixer(_:)), name: Notification.Name(rawValue: "vol1FromMixer"), object: nil)

And later at the same receiver VC:

//vol from mixer function
      @objc func vol1FromMixer() {
        _engine.setAmpGain(Double(sender.value)*2.0, ofTrack: sender.tag)
}

Got error use of unresolved identifier "sender" at the receiver VC. For sure I'm not ready with the UISlider kind of values that can be sent. Any suggestion?


Solution

  • You need to pass sender from vol1ChangedFromMixer method. You can use this method, and pass sender in userInfo. Then retrieve it in vol1FromMixer

    Sometheing like

    @IBAction func vol1ChangedFromMixer(sender: UISlider) {
        NotificationCenter.default.post(name: Notification.Name(rawValue: "vol1FromMixer"), object: nil, userInfo: ["slider": sender])
    }
    
    @objc func vol1FromMixer(_ notification: Notification) {
        guard let sender = notification.userInfo["slider"] as? UISlider
             else { return }
        _engine.setAmpGain(Double(sender.value)*2.0, ofTrack: sender.tag)
    }