你如何在 Swift 3 中创建自定义通知? [英] How do you create custom notifications in Swift 3?
本文介绍了你如何在 Swift 3 中创建自定义通知?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在 Objective-C 中,自定义通知只是一个普通的 NSString,但在 Swift 3 的 WWDC 版本中并不明显.
In Objective-C, a custom notification is just a plain NSString, but it's not obvious in the WWDC version of Swift 3 just what it should be.
推荐答案
您也可以为此使用协议
protocol NotificationName {
var name: Notification.Name { get }
}
extension RawRepresentable where RawValue == String, Self: NotificationName {
var name: Notification.Name {
get {
return Notification.Name(self.rawValue)
}
}
}
然后将您的通知名称定义为您想要的任何enum
.例如:
And then define your notification names as an enum
anywhere you want. For example:
class MyClass {
enum Notifications: String, NotificationName {
case myNotification
}
}
然后像这样使用
NotificationCenter.default.post(name: Notifications.myNotification.name, object: nil)
通过这种方式,通知名称将与 Foundation Notification.Name
分离.如果 Notification.Name
的实现发生变化,您只需修改您的协议.
This way the notification names will be decoupled from the Foundation Notification.Name
. And you will only have to modify your protocol in case the implementation for Notification.Name
changes.
这篇关于你如何在 Swift 3 中创建自定义通知?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文