使用NSNotifications在视图控制器之间传递变量

时间:2014-08-02 03:35:16

标签: swift

我试图使用NSNotifications在两个视图控制器之间传递一个整数变量,但是尽管现在已经弄清楚如何检测另一个视图控制器发送的通知,但我仍然没有想出如何实际传递一个变量在此通知中。

这是我在视图控制器中的代码,我从以下位置发送变量:

func pickerView(pickerView: UIPickerView!, didSelectRow row: Int, inComponent: Int) {
    var colourSelected = row
    println(colourSelected)
    NSNotificationCenter.defaultCenter().postNotificationName("changeColor:", object: colourSelected)
}

这是我将变量发送到的ViewController的viewDidLoad中的代码:

NSNotificationCenter.defaultCenter().addObserver(self, selector: "incomingNotification", name: "changeColor:", object: nil)

这是应该接收变量的函数:

func incomingNotification() {

if colourSelected == 0 {
println(0)
} else if colourSelected == 1 {
println(1) }

...

}

我只是收到一条错误,说colourSelected是一个未解析的标识符。

我需要改变什么?

2 个答案:

答案 0 :(得分:3)

//Sent notification 

let dictionary = ["key":"value"]    
NSNotificationCenter.defaultCenter().postNotificationName("passDataInView", object: nil, userInfo: dictionary)

 //Receive  notification 

NSNotificationCenter.defaultCenter().addObserver(self, 
   selector:"myMethod:", name: "passDataInView", object: nil)

 //Receive  notification method

   func myMethod(notification: NSNotification){

   labelName.text = notification.userInfo!["key"]

    }

答案 1 :(得分:-1)

 //Sent notification 
     NSNotificationCenter.defaultCenter().postNotificationName("passDataInView", object: nil, userInfo: passedURObject(dictionary,array,int))

 //Receive  notification 
 NSNotificationCenter.defaultCenter().addObserver(self, selector: "dataReceived", name: "passDataInView", object: getURObject(dictionary,array,int))

 //Receive  notification method
   func dataReceived(notification: NSNotification){
    //do your stuff here...
    }
相关问题