如何在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屋!
查看全文