Transmettre des données en utilisant NSNotificationCenter
Vous pouvez également transmettre des données en utilisant NotificationCenter en swift 3.0 et NSNotificationCenter en swift 2.0.
Version Swift 2.0
Transmettre des informations en utilisant userInfo qui est un dictionnaire optionnel de type [NSObject : AnyObject]?
let imageDataDict:[String: UIImage] = ["image": image]
// Poster une notification
NSNotificationCenter.defaultCenter().postNotificationName(notificationName, object: nil, userInfo: imageDataDict)
// S'inscrire pour recevoir la notification dans votre classe
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.showSpinningWheel(_:)), name: notificationName, object: nil)
// gérer la notification
func showSpinningWheel(notification: NSNotification) {
if let image = notification.userInfo?["image"] as? UIImage {
// faire quelque chose avec votre image
}
}
Version Swift 3.0
Le userInfo prend maintenant [AnyHashable:Any]? comme argument, que nous fournissons sous forme de littéral de dictionnaire en Swift
let imageDataDict:[String: UIImage] = ["image": image]
// poster une notification
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "notificationName"), object: nil, userInfo: imageDataDict)
// `default` est maintenant une propriété, pas un appel de méthode
// S'inscrire pour recevoir la notification dans votre classe
NotificationCenter.default.addObserver(self, selector: #selector(self.showSpinningWheel(_:)), name: NSNotification.Name(rawValue: "notificationName"), object: nil)
// gérer la notification
func showSpinningWheel(_ notification: NSNotification) {
if let image = notification.userInfo?["image"] as? UIImage {
// faire quelque chose avec votre image
}
}
Source transmettre des données en utilisant NotificationCenter(swift 3.0) et NSNotificationCenter(swift 2.0)
0 votes
Que demandez-vous précisément ? Comment fonctionne le sélecteur ?
1 votes
Je n'ai pas réalisé que le type "Selector" est juste une chaîne de caractères en Swift. Aucune mention dans la documentation.
0 votes
stackoverflow.com/questions/36910965/…