如何从一个视图控制器向另一个视图控制器发送和接收UISlider值

时间:2018-05-18 20:38:08

标签: swift viewcontroller uislider notificationcenter

我尝试使用NotificationCenter将滑块值(音量)发送到另一个包含我需要的所有音频引擎的视图控制器。 从发件人VC我试过这个:

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

然后在接收器VC中,在viewDidLoad中:

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

后来在同一个接收器VC:

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

错误使用未解析的标识符"发件人"在接收器VC。我肯定没有准备好可以发送的UISlider类型的值。有什么建议吗?

2 个答案:

答案 0 :(得分:0)

您需要从sender方法传递vol1ChangedFromMixer。您可以使用此method,并在sender中传递userInfo。然后在vol1FromMixer

中检索它

有些像

@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)
}

答案 1 :(得分:0)

没有通知的解决方案

1。创建类“ DataManager”

此类在我的`Tools.swift`文件中
class DataManager {
    ///to call function in VCA from VCB
    ///needs three elements:
    /// 1. this class
    /// 2. 'DataManager.shared.fistVCYouNameIt1 = self’ in VCA in viewDidLoad()
    /// 3. 'DataManager.shared.fistVCYouNameIt1.myFuncInVcAToCallFromVcB()' in VCB (execute function in VCA)
    static let shared = DataManager()
    var fistVCYouNameIt1 = ViewController1() //class Name
    var fistVCYouNameIt2 = ViewController1() //class Name
    //var fistVCYouNameIt3 ...
}//end class DataManager

2。在您的VCA中,在viewDidLoad()中:

override func viewDidLoad() {
    super.viewDidLoad()
    DataManager.shared.fistVCYouNameIt1 = self //to call func ‘myFuncInVcAToCallFromVcB ()’ from VCB in VCA. Without this e.g. your outlets are not accessible within VCA, when called from VCB

    //other code
}

3。在您的VCB中

您的代码VCB中要调用VCA中的函数的点:
...
DataManager.shared.fistVCYouNameIt.myFuncInVcAToCallFromVcB() //execute func in VCA 
...

4。在您的VCA中:

func myFuncInVcAToCallFromVcB (){
    //your code here
}