Swift 使用NSNotifications在视图控制器之间传递变量
我试图使用NSNotifications在两个视图控制器之间传递一个整数变量,但是,尽管现在已经知道如何检测另一个视图控制器发送的通知,我仍然没有知道如何在该通知中实际传递一个变量 这是我从视图控制器中发送变量的代码:Swift 使用NSNotifications在视图控制器之间传递变量,swift,Swift,我试图使用NSNotifications在两个视图控制器之间传递一个整数变量,但是,尽管现在已经知道如何检测另一个视图控制器发送的通知,我仍然没有知道如何在该通知中实际传递一个变量 这是我从视图控制器中发送变量的代码: func pickerView(pickerView: UIPickerView!, didSelectRow row: Int, inComponent: Int) { var colourSelected = row println(colourSelecte
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) }
...
}
我刚刚收到一个错误,说colorselected是一个未解析的标识符
我需要更改什么?所以我尝试了“NSNotificationCenter.defaultCenter()。postNotificationName(“colorSelectedPass”,object:nil,userInfo:colorSelected)userInfo是一个字典。所以你的对象作为字典传递。字典设置你的int值。哈是对的。这里的帖子应该有一些合理的语法标准。
//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...
}
//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"]
}