swift中通知NSNotificationCenter的使用
发布时间:2020-12-14 06:17:48 所属栏目:百科 来源:网络整理
导读:github 学习地址: https://github.com/potato512/SYSwiftLearning 使用通知注意事项: (1)接收通知前必须先移除掉通知,避免只发一次通知时,却出现两次或多次的响应事件; (2)使用通知的类在被释放时,必须要移除通知; 效果图: 代码示例: func send
github学习地址:https://github.com/potato512/SYSwiftLearning 使用通知注意事项: (1)接收通知前必须先移除掉通知,避免只发一次通知时,却出现两次或多次的响应事件; (2)使用通知的类在被释放时,必须要移除通知; 效果图: 代码示例:
func sendNotification() { // 发送通知 // 无参数 // NSNotificationCenter.defaultCenter().postNotificationName("ChangeBackgroundColor",object: nil,userInfo: nil) // 带参数 let number = random() % 1000 let numberString = ("(number)" as String) let dict = ["number":numberString]; NSNotificationCenter.defaultCenter().postNotificationName("ChangeBackgroundColor",object: dict) // NSNotificationCenter.defaultCenter().postNotificationName("ChangeBackgroundColor",object: self,userInfo: uderInfo) } func addNotification() { // 接收通知 // 先移除通知 NSNotificationCenter.defaultCenter().removeObserver(self,name: "ChangeBackgroundColor",object: nil) // 无参数 // NSNotificationCenter.defaultCenter().addObserver(self,selector: Selector("notificationAction"),object: nil) // 带参数 NSNotificationCenter.defaultCenter().addObserver(self,selector: Selector("notificationAction:"),object: nil) } // func notificationAction() // 无参数 func notificationAction(notification:NSNotification) // 带参数 { // 通知响应方法 let color = UIColor.init(red: (((CGFloat)(random() % 256) / 255.0)),green: (((CGFloat)(random() % 256) / 255.0)),blue: (((CGFloat)(random() % 256) / 255.0)),alpha: 1.0) self.view.backgroundColor = color // 参数 let name = notification.name let dict = notification.object let numberText = dict?.valueForKey("number") as! String let text = "通知名称:(name),传值:(numberText)" label.text = text } deinit { // 移除通知 NSNotificationCenter.defaultCenter() .removeObserver(self) print("(self) 被释放了") } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |